golang 取得本机出口IP

  1. package main
  2. import (
  3. "log"
  4. "net"
  5. )
  6. // Get preferred outbound ip of this machine
  7. func GetOutboundIP() string {
  8. conn, err := net.Dial("udp", "223.5.5.5:53")
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. defer conn.Close()
  13. localAddr := conn.LocalAddr().(*net.UDPAddr)
  14. return localAddr.IP.String()
  15. }
  16. func main() {
  17. log.SetFlags(log.Lshortfile)
  18. log.Println(GetOutboundIP()) // main.go:21: 172.31.0.8
  19. }