douge3830 2014-05-08 23:00
浏览 289
已采纳

如何在Go中获取本地IP地址?

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

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
", err)
     return
}

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

for _, a := range addrs {
    fmt.Println(a)
}  
  • 写回答

7条回答 默认 最新

  • du4010 2014-05-08 23:05
    关注

    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
        }
    }
    

    Play (taken from util/helper.go)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部