如何获取分配给机器的所有IP地址?

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

How do I get all IP addresses assigned to the machine?

问题

给定以下代码:

// iptest
package main

import (
    "fmt"
    "net"
    "os"
)

func main() {
    host, _ := os.Hostname()
    addrs, _ := net.LookupIP(host)
    for _, addr := range addrs {
        if ipv4 := addr.To4(); ipv4 != nil {
            fmt.Println("IPv4: ", ipv4)
        }
    }
}

我遇到的问题是它只返回分配给适配器的第一个IP地址。这似乎只是在定义了DNS后缀的系统上出现的问题。如果没有定义DNS后缀,它可以正常工作并报告所有已分配的IP地址。

英文:

Given the following code:

// iptest
package main

import (
    "fmt"
    "net"
    "os"
)

func main() {
    host, _ := os.Hostname()
    addrs, _ := net.LookupIP(host)
    for _, addr := range addrs {
        if ipv4 := addr.To4(); ipv4 != nil {
    	    fmt.Println("IPv4: ", ipv4)
	    }   
    }
}

I'm having a problem where it only returns the first IP address assigned to the adapter. This appears to be a problem only on systems that have a DNS suffix defined. If one is not defined, it works fine and reports all IPs that have been assigned.

答案1

得分: 6

如果你想获取当前分配给机器的地址,我认为你应该考虑使用net.InterfaceAddrs()而不是尝试通过主机名进行DNS查找。以下是一个简短的示例,可以给出本地机器上的所有IP地址。

package main

import (
    "fmt"
    "net"
)

func main() {
    addrs, _ := net.InterfaceAddrs()
    fmt.Printf("%v\n", addrs)
    for _, addr := range addrs {
        fmt.Println("IPv4: ", addr)
    }
}
英文:

If you're trying to get the addresses currently assigned to the machine. I think you should consider using net.InterfaceAddrs() instead of trying to do a DNS lookup for the hostname. Here's a short example that will give you all the IPs on the local machine.

package main

import (
    "fmt"
    "net"
)

func main() {
    addrs, _ := net.InterfaceAddrs()
    fmt.Printf("%v\n", addrs)
    for _, addr := range addrs {
        fmt.Println("IPv4: ", addr)
    }
}

huangapple
  • 本文由 发表于 2016年2月10日 23:40:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/35319515.html
匿名

发表评论

匿名网友

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

确定