ip.go 670 B

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