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

victor picture victor · Aug 29, 2011 · Viewed 22.8k times · Source

Now I need to get the status of the NIC(up or down) in the real time. That means I have to catch the kernel interrupt when the NIC up or down in a blocked loop.

The first stupid method from mine is that check on the /sys/class/net/eth0/operstate or use ioctl to get the ifflag every 100ms in a loop. But 100ms is too long for the app to reroute the traffic and also polling kernel every 100ms is not good idea.

Once I notice the inotify function that can monitor the files in a block mode. But unfortunately, it can't monitor the /sys/class/net/eth0/operstate file since /sys is located in the RAM not in the disk.

So, is there any methods except writing a kernel module to catch the NIC interrupt(up/down) in the C program with a block mode?

Answer

gby picture gby · Aug 29, 2011

Yes, open a netlink socket and listen to the RTMGRP_LINK (network interface create/delete/up/down events) multicast groups.

The netlink man page here has a specific example to do this.