How do I get the local IP address in Go?

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

    To ensure that you get a non-loopback address, simply check that an IP is not a loopback when you are iterating.

    // GetLocalIP returns the non loopback local IP of the host
    func GetLocalIP() string {
        addrs, err := net.InterfaceAddrs()
        if err != nil {
            return ""
        }
        for _, address := range addrs {
            // check the address type and if it is not a loopback the display it
            if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
                if ipnet.IP.To4() != nil {
                    return ipnet.IP.String()
                }
            }
        }
        return ""
    }
    

提交回复
热议问题