Golang obtain network card information

Time:2022-6-5

I won’t say any more nonsense. Let’s just look at the code~


package main
import (
	"fmt"
	"os/exec"
	"strings"
	"github.com/safchain/ethtool"
)
func main() {
	baseNicPath := "/sys/class/net/"
	cmd := exec.Command("ls", baseNicPath)
	buf, err := cmd.Output()
	if err != nil {
		//fmt.Println("Error:", err)
		return
	}
	output := string(buf)
	for _, device := range strings.Split(output, "\n") {
		if len(device) > 1 {
			fmt.Println(device)
			ethHandle, err := ethtool.NewEthtool()
			if err != nil {
				panic(err.Error())
			}
			defer ethHandle.Close()
			stats, err := ethHandle.LinkState(device)
			if err != nil {
				panic(err.Error())
			}
			fmt.Printf("LinkName: %s LinkState: %d\n", device, stats)
		}
	}
}
©

Supplement: go language obtains the Ethernet type network card address

Obtain the Ethernet type network card address in c\

In c\ NetworkInterfaceType == NetworkInterfaceType. Ethernet therefore, it is easy to judge in the code.


public static PhysicalAddress GetMacAddress()
{
  foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  {
    // Only consider Ethernet network interfaces
    if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) // nic.OperationalStatus == OperationalStatus.Up
    {
      return nic.GetPhysicalAddress();
    }
  }
  return null;
}

Handling method in go

After searching Baidu hundreds of times, I didn’t find the answer. But I searched the source code of the net package to find clues. In the unpublished method, I found a type of judgment statement. net/interface_ windows. In go, there is case windows IF_ TYPE_ ETHERNET_ Type judgment of csmacd.

Find if again_ TYPE_ ETHERNET_ Csmacd information is exactly what is needed here.

reference resources:IP_INTERFACE_NAME_INFO_W2KSP1 structure

Therefore, the required part is copied and transformed to obtain the isethernet method. In combination with the existing methods in the net package, the parameters are net Interface.

The complete code is as follows:

package machine 
import (
  "errors"
  "net"
  "os"
  "strings"
  "syscall"
  "unsafe" 
  "golang.org/x/sys/windows"
)
 
func GetMACAddress() (string, error) {
  netInterfaces, err := net.Interfaces()
  if err != nil {
    panic(err.Error())
  }
 
  mac, macerr := "", errors.New("no valid mac address")
  for i := 0; i < len(netInterfaces); i++ {
    if (netInterfaces[i].Flags&net.FlagLoopback) == 0 && strings.Contains(netInterfaces[i].Flags.String(), "broadcast") {
      index := netInterfaces[i].Index
 
      if isEthernet(index) {
        mac = netInterfaces[i].HardwareAddr.String()
        return mac, nil
      }
    }
  }
  return mac, macerr
}
 
//Judge whether it is an Ethernet network card according to the network card interface index
func isEthernet(ifindex int) bool {
  aas, err := adapterAddresses()
  if err != nil {
    return false
  }
  result := false
  for _, aa := range aas {
    index := aa.IfIndex
    if ifindex == int(index) {
      switch aa.IfType {
      case windows.IF_TYPE_ETHERNET_CSMACD:
        result = true
      }
 
      if result {
        break
      }
    }
  }
  return result
}
 
//From net/interface_ windows. Copy from go
func adapterAddresses() ([]*windows.IpAdapterAddresses, error) {
  var b []byte
  l := uint32(15000) // recommended initial size
  for {
    b = make([]byte, l)
    err := windows.GetAdaptersAddresses(syscall.AF_UNSPEC, windows.GAA_FLAG_INCLUDE_PREFIX, 0, (*windows.IpAdapterAddresses)(unsafe.Pointer(&b[0])), &l)
    if err == nil {
      if l == 0 {
        return nil, nil
      }
      break
    }
    if err.(syscall.Errno) != syscall.ERROR_BUFFER_OVERFLOW {
      return nil, os.NewSyscallError("getadaptersaddresses", err)
    }
    if l <= uint32(len(b)) {
      return nil, os.NewSyscallError("getadaptersaddresses", err)
    }
  }
  var aas []*windows.IpAdapterAddresses
  for aa := (*windows.IpAdapterAddresses)(unsafe.Pointer(&b[0])); aa != nil; aa = aa.Next {
    aas = append(aas, aa)
  }
  return aas, nil
}

The above is my personal experience. I hope I can give you a reference, and I hope you can support developeppaer. If there is any mistake or not fully considered, please don’t hesitate to comment.