goProject/trunk/goutil/netUtil/getLocalIP.go
皮蛋13361098506 1b77f62820 初始化项目
2025-01-06 16:01:02 +08:00

41 lines
783 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package netUtil
import (
"errors"
"net"
)
// 需要排除的IP: 169.254.xx.xx (未分配到IP的段)
func excludeIP(ip4 net.IP) bool {
return ip4[0] == 169 && ip4[1] == 254
}
// GetLocalIPs
//
// @Description: 获取本机局域网IP排除环回地址
// @return ips
// @return err
func GetLocalIPs() (ips []string, err error) {
var addrs []net.Addr
if addrs, err = net.InterfaceAddrs(); err != nil {
return
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() /*&& ipnet.IP.IsPrivate()*/ {
if ip4 := ipnet.IP.To4(); ip4 != nil {
if !excludeIP(ip4) {
ips = append(ips, ipnet.IP.String())
}
}
}
}
if len(ips) == 0 {
// 未获取到本机局域网IP
err = errors.New("not found")
}
return
}