package main import ( "fmt" "net" "os" ) func main() { addrs, err: = net.InterfaceAddrs() if err != nil { fmt.Println(err) os.Exit(1) } for _, addr: = range addrs { if ipnet, ok: = addr.( * net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { fmt.Println("IPv4: ", ipnet.IP.String()) } } } }运行结果:
IPv4: 169.254.157.225 IPv4: 169.254.28.142 IPv4: 169.254.211.187 IPv4: 192.168.144.1 IPv4: 192.168.253.1 IPv4: 10.252.64.116 IPv4: 169.254.106.194 IPv4: 169.254.109.149 IPv4: 172.28.240.1甚至比我在终端使用ipconfig命令得到的IPv4地址还要多。
package main import ( "fmt" "net" "os" ) func main() { interfaces, err: = net.Interfaces() if err != nil { fmt.Println(err) os.Exit(1) } for _, i: = range interfaces { if i.Name == "WLAN" { addrs, err: = i.Addrs() if err != nil { fmt.Println(err) continue } for _, addr: = range addrs { if ipnet, ok: = addr.( * net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { fmt.Println("IPv4: ", ipnet.IP.String()) } } } } } }运行结果:
IPv4: 10.252.64.116
经过和上图比对,结果正确。
package main // 堆代码 duidaima.com import ( "fmt" "net" ) func main() { conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { fmt.Println(err) return } defer conn.Close() localAddr := conn.LocalAddr().(*net.UDPAddr) fmt.Println("My public IP address is:", localAddr.IP.String()) }运行结果:
My public IP address is: 10.252.64.116经过比对,结果正确。我们可以发现如果我们的电脑是用WiFi上网的,用此方法得出的结果与WLAN的IPv4地址相同。
package main import ( "fmt" "io/ioutil" "net/http" ) func main() { resp, err: = http.Get("https://api.ipify.org") if err != nil { fmt.Println(err) return } defer resp.Body.Close() ip, err: = ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println("My public IP address is: ", string(ip)) }除了使用 https://api.ipify.org,还有其他一些服务可以提供公网IP地址,例如 https://ifconfig.me 和 https://icanhazip.com。