英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论