Golang取局域网地址,方法有不少,我就把自己常用的几种整理出来,附带了IP校验。代码如下:

package main
import (
"log"
"os"
"os/exec"
"bytes"
"net"
"strings"
)
var localIP string

func main() {
log.SetFlags(0)
host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
for _, addr := range addrs {
if ipv4 := addr.To4(); ipv4 != nil {
localIP = ipv4.String()
break
}
}
log.Print("localIP:"+localIP)
address := net.ParseIP(localIP)
if localIP=="" || address == nil {
cmd := exec.Command("/bin/bash", "-c", "ip addr |grep inet |grep -v inet6|sed -n '2p'|cut -f 1 -d \"/\"|awk '{print $2}'")
var out bytes.Buffer
cmd.Stdout = &out
cmd.Run()
localIP = out.String()
localIP = strings.Replace(localIP, "\r", "", -1)
localIP = strings.Replace(localIP, "\n", "", -1)
log.Print("localIP:"+localIP)
}
address = net.ParseIP(localIP)
if localIP=="" || address == nil {
ifaces, err := net.Interfaces()
if err != nil {
// handle error
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
// handle error
}
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
localIP = v.IP.String()
case *net.IPAddr:
localIP = v.IP.String()
}
}
}
log.Print("localIP:"+localIP)
}
address = net.ParseIP(localIP)
if localIP=="" || address == nil {
log.Print("localIP blank")
}
}

参考资料:https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go

Related Posts: Golang取局域网地址方法 :

avatar