Site icon 时鹏亮的Blog

Golang取局域网地址方法

请知悉:本文最近一次更新为 5年 前,文中内容可能已经过时。

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


如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《Golang取局域网地址方法》相关的博文:

Exit mobile version