github.com/aporeto-inc/trireme-lib@v10.358.0+incompatible/utils/netinterfaces/netinterfaces.go (about)

     1  package netinterfaces
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  
     7  	"go.uber.org/zap"
     8  )
     9  
    10  // NetworkInterface holds info of a network interface
    11  type NetworkInterface struct {
    12  	Name   string
    13  	IPs    []net.IP
    14  	IPNets []*net.IPNet
    15  	Flags  net.Flags
    16  }
    17  
    18  // GetInterfacesInfo returns interface info
    19  func GetInterfacesInfo() ([]NetworkInterface, error) {
    20  
    21  	netInterfaces := []NetworkInterface{}
    22  
    23  	// List interfaces
    24  	ifaces, err := net.Interfaces()
    25  	if err != nil {
    26  		return nil, fmt.Errorf("unable to get interfaces: %v", err)
    27  	}
    28  
    29  	for _, intf := range ifaces {
    30  		ipList := []net.IP{}
    31  		ipNetList := []*net.IPNet{}
    32  
    33  		// List interface addresses
    34  		addrs, err := intf.Addrs()
    35  		if err != nil {
    36  			zap.L().Warn("unable to get interface addresses",
    37  				zap.String("interface", intf.Name),
    38  				zap.Error(err))
    39  			continue
    40  		}
    41  
    42  		for _, addr := range addrs {
    43  			ip, ipNet, err := net.ParseCIDR(addr.String())
    44  			if err != nil {
    45  				zap.L().Warn("unable to parse address",
    46  					zap.String("interface", intf.Name),
    47  					zap.String("addr", addr.String()),
    48  					zap.Error(err))
    49  				continue
    50  			}
    51  
    52  			ipList = append(ipList, ip)
    53  			ipNetList = append(ipNetList, ipNet)
    54  		}
    55  
    56  		netInterface := NetworkInterface{
    57  			Name:   intf.Name,
    58  			IPs:    ipList,
    59  			IPNets: ipNetList,
    60  			Flags:  intf.Flags,
    61  		}
    62  
    63  		netInterfaces = append(netInterfaces, netInterface)
    64  	}
    65  
    66  	return netInterfaces, nil
    67  }