英文:
how to get free ip in range 127.0.0.1 - 127.0.x.255 with golang?
问题
我想从地址范围中获取计算机的免费本地IP地址。
net.LookupHost只会返回127.0.0.1或公共IP地址。
net.LookupHost(name)
英文:
I want to get the computer's free local IP address from range of addresses.
net.LookupHost will return only 127.0.0.1 or public ip addresses.
net.LookupHost(name)
答案1
得分: 1
也许下面的函数可以帮助你:
func getLocalhostIP() string {
netInterfaces, err := net.Interfaces()
if err != nil {
log.Errorf("net.Interfaces failed, err:", err)
return ""
}
for i := 0; i < len(netInterfaces); i++ {
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
addrs, _ := netInterfaces[i].Addrs()
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
}
}
return ""
}
希望对你有帮助!
英文:
Maybe this function below can help you:
func getLocalhostIP() string {
netInterfaces, err := net.Interfaces()
if err != nil {
log.Errorf("net.Interfaces failed, err:", err)
return ""
}
for i := 0; i < len(netInterfaces); i++ {
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
addrs, _ := netInterfaces[i].Addrs()
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
}
}
return ""
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论