如何在Go中获取本地IP地址? [英] How do I get the local IP address in Go?

查看:345
本文介绍了如何在Go中获取本地IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取计算机的IP地址.我使用了下面的代码,但它返回了127.0.0.1.

I want to get the computer's IP address. I used the code below, but it returns 127.0.0.1.

我想获取IP地址,例如10.32.10.111,而不是回送地址.

I want to get the IP address, such as 10.32.10.111, instead of the loopback address.

name, err := os.Hostname()
if err != nil {
     fmt.Printf("Oops: %v\n", err)
     return
}

addrs, err := net.LookupHost(name)
if err != nil {
    fmt.Printf("Oops: %v\n", err)
    return
}

for _, a := range addrs {
    fmt.Println(a)
}  

推荐答案

您需要遍历所有网络接口

You need to loop through all network interfaces

ifaces, err := net.Interfaces()
// handle err
for _, i := range ifaces {
    addrs, err := i.Addrs()
    // handle err
    for _, addr := range addrs {
        var ip net.IP
        switch v := addr.(type) {
        case *net.IPNet:
                ip = v.IP
        case *net.IPAddr:
                ip = v.IP
        }
        // process IP address
    }
}

播放(取自util/helper.go)

Play (taken from util/helper.go)

这篇关于如何在Go中获取本地IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆