ip.go 632 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package netx
  2. import "net"
  3. func InternalIp() string {
  4. infs, err := net.Interfaces()
  5. if err != nil {
  6. return ""
  7. }
  8. for _, inf := range infs {
  9. if isEthDown(inf.Flags) || isLoopback(inf.Flags) {
  10. continue
  11. }
  12. addrs, err := inf.Addrs()
  13. if err != nil {
  14. continue
  15. }
  16. for _, addr := range addrs {
  17. if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  18. if ipnet.IP.To4() != nil {
  19. return ipnet.IP.String()
  20. }
  21. }
  22. }
  23. }
  24. return ""
  25. }
  26. func isEthDown(f net.Flags) bool {
  27. return f&net.FlagUp != net.FlagUp
  28. }
  29. func isLoopback(f net.Flags) bool {
  30. return f&net.FlagLoopback == net.FlagLoopback
  31. }