golang 取得本机出口IP
package main
import (
"log"
"net"
)
// Get preferred outbound ip of this machine
func GetOutboundIP() string {
conn, err := net.Dial("udp", "223.5.5.5:53")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP.String()
}
func main() {
log.SetFlags(log.Lshortfile)
log.Println(GetOutboundIP()) // main.go:21: 172.31.0.8
}