How do I get the local IP address in Go?

后端 未结 8 1452
花落未央
花落未央 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:34

    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)

提交回复
热议问题