How do I get the local IP address in Go?

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

    func resolveHostIp() (string) {
    
        netInterfaceAddresses, err := net.InterfaceAddrs()
    
        if err != nil { return "" }
    
        for _, netInterfaceAddress := range netInterfaceAddresses {
    
            networkIp, ok := netInterfaceAddress.(*net.IPNet)
    
            if ok && !networkIp.IP.IsLoopback() && networkIp.IP.To4() != nil {
    
                ip := networkIp.IP.String()
    
                fmt.Println("Resolved Host IP: " + ip)
    
                return ip
            }
        }
        return ""
    }
    

提交回复
热议问题