goProject/.svn/pristine/71/71d3a41dbac37c4407fb1d7c8b8d533f0e3c5db3.svn-base

41 lines
783 B
Plaintext
Raw Normal View History

2025-01-06 16:21:36 +08:00
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
}