net.go 950 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package util
  2. import (
  3. "net"
  4. "regexp"
  5. externalip "github.com/glendc/go-external-ip"
  6. )
  7. // Interfaces returns a `name:ip` map of the suitable interfaces found
  8. func Interfaces(listAll bool) (map[string]string, error) {
  9. names := make(map[string]string)
  10. ifaces, err := net.Interfaces()
  11. if err != nil {
  12. return names, err
  13. }
  14. var re = regexp.MustCompile(`^(veth|br\-|docker|lo|EHC|XHC|bridge|gif|stf|p2p|awdl|utun|tun|tap)`)
  15. for _, iface := range ifaces {
  16. if !listAll && re.MatchString(iface.Name) {
  17. continue
  18. }
  19. if iface.Flags&net.FlagUp == 0 {
  20. continue
  21. }
  22. ip, err := FindIP(iface)
  23. if err != nil {
  24. continue
  25. }
  26. names[iface.Name] = ip
  27. }
  28. return names, nil
  29. }
  30. // GetExernalIP of this host
  31. func GetExernalIP() (net.IP, error) {
  32. consensus := externalip.DefaultConsensus(nil, nil)
  33. // Get your IP, which is never <nil> when err is <nil>
  34. ip, err := consensus.ExternalIP()
  35. if err != nil {
  36. return nil, err
  37. }
  38. return ip, nil
  39. }