如何使用Golang在127.0.0.1 – 127.0.x.255范围内获取免费IP?

huangapple go评论79阅读模式
英文:

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(&quot;net.Interfaces failed, err:&quot;, err)
    		return &quot;&quot;
    	}
    
    	for i := 0; i &lt; len(netInterfaces); i++ {
    		if (netInterfaces[i].Flags &amp; net.FlagUp) != 0 {
    			addrs, _ := netInterfaces[i].Addrs()
    
    			for _, address := range addrs {
    				if ipnet, ok := address.(*net.IPNet); ok &amp;&amp; !ipnet.IP.IsLoopback() {
    					if ipnet.IP.To4() != nil {
    						return ipnet.IP.String()
    					}
    				}
    			}
    		}
    	}
    	return &quot;&quot;
    }

huangapple
  • 本文由 发表于 2022年5月27日 17:04:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/72403001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定