I need a way to notify my user space app when a network interface is enabled or disabled. I'm hoping to do this without resorting to polling. Does the kernel offer some sort of hook for triggering callback functions when network-related events occur?
I believe the netlink (man 7 netlink
) facility provides information about network interfaces via the NETLINK_ROUTE
family (man 7 rtnetlink
). You may be able to select()
or poll()
on a netlink socket to get the information you want. I'm not certain of this, though; I haven't used it myself.
At a higher level, if the system is running NetworkManager, that'll broadcast events via D-Bus when the system's network status changes. The Epiphany browser uses these events, for example, to automatically activate "Work Offline" mode when the system loses its network connection, and switch back to online mode when network connectivity resumes. There are D-Bus client libraries for a variety of languages, and it's less platform-specific than netlink, so this is what I'd recommend using.
Options:
ifplugd
will run the script of your choice when a cable is plugged into or unplugged from your network interface.If you are using Debian you can add a script to the subdirectories of
/etc/network
, where there are scripts that are run every time an interface goes up or down.If neither of the above are suitable for your needs, look into D-Bus. I've never had much luck using it successfully, but this is the sort of thing it was designed for.
In Debian version 12 (Bookworm) the files in the following folder get executed on interface changes: /etc/NetworkManager/dispatcher.d/ I have added a second file 02-ifupdown to the raspberry pi I am using. The file gets passed args $1 & $2 as interface name and status.
Why not do a fork
in the code, using popen
to do either:
- Issue
tail -f /var/log/messages
looking foreth*
interfaces - Issue
ifconfig
to see the list of adapters going up or down
and parse the data using a pregex
, do a sleep()
for a period of time and recheck again.. Or you could go monitor the system log facility using the 'syslog.h' functions.
If you stick to the Posix standard, the code will be portable across different flavours of Unix/Linux/BSD...
ifconfig
isn't POSIX and the output actually varies quite a lot from one UNIX to another. Sure, it's (mostly) the same on all Linuxes, but even there there's two different versions in common use (Busybox's and net-tools's). –
Carvey /var/log/messages
isn't a file you can rely on as any sort of API. It's for human-readable logging. On some systems, logs go to /var/log/syslog
. Who knows if logs might be at a different filename, or disabled, or in a different text format than expected. A program might be confused by other log entries that refer to eth*
. –
Cutinize © 2022 - 2024 — McMap. All rights reserved.