Advertisement
Kala666

inetinfo.go

Mar 27th, 2019
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.42 KB | None | 0 0
  1. // InetInfo gathers information about different net interfaces and their
  2. // IP addresses and returns that as a string for debug purposes.
  3. // Returns an error string if errors occurred.
  4. func InetInfo() string {
  5.     // Loop over all the interfaces
  6.     ifaces, err := net.Interfaces()
  7.     if err != nil {
  8.         return fmt.Sprintf("Error retrieving interfaces: %v", err.Error())
  9.     }
  10.  
  11.     // This will map interface name to textual representations of its
  12.     // IP addresses
  13.     addrMap := map[string][]string{}
  14.  
  15.     for _, i := range ifaces {
  16.         // Loop over all addresses for that interface
  17.         addrs, err := i.Addrs()
  18.         if err != nil {
  19.             return fmt.Sprintf("Error retrieving addresses: %v", err.Error())
  20.         }
  21.  
  22.         addrList := make([]string, 0)
  23.  
  24.         for _, addr := range addrs {
  25.             var ip net.IP
  26.             switch v := addr.(type) {
  27.             case *net.IPAddr:
  28.                 ip = v.IP
  29.             case *net.IPNet:
  30.                 ip = v.IP
  31.             default:
  32.                 // Skip others
  33.                 continue
  34.             }
  35.  
  36.             addr := ""
  37.             if ipv4 := ip.To4(); ipv4 != nil {
  38.                 addr = fmt.Sprintf("  IPv4 addr: %v", ip.String())
  39.             } else {
  40.                 addr = fmt.Sprintf("  IPv6 addr: %v", ip.String())
  41.             }
  42.             addrList = append(addrList, addr)
  43.         }
  44.  
  45.         if len(addrList) > 0 {
  46.             addrMap[i.Name] = addrList
  47.         }
  48.     }
  49.  
  50.     s := ""
  51.     for ifName, addrList := range addrMap {
  52.         s += fmt.Sprintf("\n\nInterface: %v", ifName)
  53.         for _, a := range addrList {
  54.             s += fmt.Sprintf("\n  %v", a)
  55.         }
  56.     }
  57.  
  58.     return strings.TrimLeft(s, "\n ")
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement