You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
788 B
42 lines
788 B
package nets |
|
|
|
import ( |
|
"errors" |
|
"net" |
|
) |
|
|
|
// GetHostIpv4 获取本地内网IP |
|
func GetHostIpv4() (string, error) { |
|
privates, err := getAllIPV4(func(ip net.IP) bool { |
|
return ip.IsPrivate() |
|
}) |
|
if err != nil { |
|
return "", err |
|
} |
|
if len(privates) == 0 { |
|
return "", errors.New("no private ip") |
|
} |
|
return privates[0], nil |
|
} |
|
|
|
func getAllIPV4(filter func(net.IP) bool) (ips []string, err error) { |
|
// 获取所有网卡 |
|
addrs, err := net.InterfaceAddrs() |
|
if err != nil { |
|
return |
|
} |
|
|
|
for _, addr := range addrs { |
|
// 这个网络地址是IP地址: ipv4, ipv6 |
|
ipNet, isIpNet := addr.(*net.IPNet) |
|
if isIpNet && !ipNet.IP.IsLoopback() { |
|
// 跳过IPV6 |
|
if ipNet.IP.To4() != nil { |
|
if filter(ipNet.IP) { |
|
ips = append(ips, ipNet.IP.String()) |
|
} |
|
} |
|
} |
|
} |
|
return |
|
}
|
|
|