How do I get the local IP address in Go?

后端 未结 8 1429
花落未央
花落未央 2020-12-02 07:04

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

8条回答
  •  情歌与酒
    2020-12-02 07:28

    This worked for me:

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

    Unlike the poster's example, it returns only non-loopback addresses, e.g. 10.120.X.X.

提交回复
热议问题