Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...