How do I get the local IP address in Go?

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

    func GetInternalIP() string {
        itf, _ := net.InterfaceByName("enp1s0") //here your interface
        item, _ := itf.Addrs()
        var ip net.IP
        for _, addr := range item {
            switch v := addr.(type) {
            case *net.IPNet:
                if !v.IP.IsLoopback() {
                    if v.IP.To4() != nil {//Verify if IP is IPV4
                        ip = v.IP
                    }
                }
            }
        }
        if ip != nil {
            return ip.String()
        } else {
            return ""
        }
    }
    

提交回复
热议问题