2

As per below link, i understood that by creating netlink socket and listen to the RTMGRP_LINK we can detect events(network interface create/delete/up/down events).

How can I monitor the NIC status(up/down) in a C program without polling the kernel?

Is it possible to get the pci address of a newly added interface once it is detected?

Community
  • 1
  • 1
user1762571
  • 1,888
  • 7
  • 28
  • 47

1 Answers1

6

Once you know its interface name (such as eth0) you can query that info with the ethtool API:

#include <linux/ethtool.h> 
#include <linux/sockios.h>
.. and other socket headers.
...

 int sock = socket(PF_INET, SOCK_DGRAM, 0);

 struct ifreq ifr;
 struct ethtool_cmd cmd;
 struct ethtool_drvinfo drvinfo;

 memset(&ifr, 0, sizeof ifr);
 memset(&cmd, 0, sizeof cmd);
 memset(&drvinfo, 0, sizeof drvinfo);
 strcpy(ifr.ifr_name, "eno1");

 ifr.ifr_data = &drvinfo;
 drvinfo.cmd = ETHTOOL_GDRVINFO;

 if(ioctl(sock, SIOCETHTOOL, &ifr) < 0) {
    perror("ioctl")
    return;
 }

Now the PCI bus address is available as a string in drvinfo.bus_info - given that the NIC is actually a PCI device.

You can check this via the command line too:

$ ethtool -i eno1
driver: e1000e
version: 2.3.2-k
firmware-version: 0.13-4
bus-info: 0000:00:19.0
supports-statistics: yes
supports-test: yes
supports-eeprom-access: yes
supports-register-dump: yes
supports-priv-flags: no
nos
  • 223,662
  • 58
  • 417
  • 506