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

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

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

也许下面的函数可以帮助你:

  1. func getLocalhostIP() string {
  2. netInterfaces, err := net.Interfaces()
  3. if err != nil {
  4. log.Errorf("net.Interfaces failed, err:", err)
  5. return ""
  6. }
  7. for i := 0; i < len(netInterfaces); i++ {
  8. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  9. addrs, _ := netInterfaces[i].Addrs()
  10. for _, address := range addrs {
  11. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  12. if ipnet.IP.To4() != nil {
  13. return ipnet.IP.String()
  14. }
  15. }
  16. }
  17. }
  18. }
  19. return ""
  20. }

希望对你有帮助!

英文:

Maybe this function below can help you:

  1. func getLocalhostIP() string {
  2. netInterfaces, err := net.Interfaces()
  3. if err != nil {
  4. log.Errorf(&quot;net.Interfaces failed, err:&quot;, err)
  5. return &quot;&quot;
  6. }
  7. for i := 0; i &lt; len(netInterfaces); i++ {
  8. if (netInterfaces[i].Flags &amp; net.FlagUp) != 0 {
  9. addrs, _ := netInterfaces[i].Addrs()
  10. for _, address := range addrs {
  11. if ipnet, ok := address.(*net.IPNet); ok &amp;&amp; !ipnet.IP.IsLoopback() {
  12. if ipnet.IP.To4() != nil {
  13. return ipnet.IP.String()
  14. }
  15. }
  16. }
  17. }
  18. }
  19. return &quot;&quot;
  20. }

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:

确定