Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get notified about network interface change on Linux

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?

like image 617
live2dream95 Avatar asked Feb 14 '10 16:02

live2dream95


2 Answers

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.

like image 159
Wyzard Avatar answered Oct 07 '22 15:10

Wyzard


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.

like image 26
Norman Ramsey Avatar answered Oct 07 '22 14:10

Norman Ramsey