How do I get the local IP address in Go?

后端 未结 8 1293
花落未央
花落未央 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 ""
    }
    
    0 讨论(0)
  • 2020-12-02 07:45

    Here is a better solution to retrieve the preferred outbound ip address when there are multiple ip interfaces exist on the machine.

    import (
        "log"
        "net"
        "strings"
    )
    
    // Get preferred outbound ip of this machine
    func GetOutboundIP() net.IP {
        conn, err := net.Dial("udp", "8.8.8.8:80")
        if err != nil {
            log.Fatal(err)
        }
        defer conn.Close()
    
        localAddr := conn.LocalAddr().(*net.UDPAddr)
    
        return localAddr.IP
    }
    
    0 讨论(0)
提交回复
热议问题