raj
raj

Reputation: 175

detect network interface change

My UBUNTU machine is having two network interface ports. I want to write an application in C/C++ where I can detect changes in network interface and print the result.

e.g. When two network cables are connected then application should print both interfaces are up. When I unplug one cable then application should remove all information of that interface and print which interface is down and up.

Upvotes: 2

Views: 3166

Answers (1)

SKi
SKi

Reputation: 8466

You can poll status of links with ioctl():

struct ifreq ifr;

memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, "eth0");

if (ioctl(fd, SIOCGIFFLAGS, &ifr) != -1)
{
    up_and_running = (ifr.ifr_flags & ( IFF_UP | IFF_RUNNING )) == ( IFF_UP | IFF_RUNNING );
}

If you want immediately information about changes, then listen netlink messages from kernel.

See man page PF_NETLINK(7).

For creating AF_NETLINK socket for getting link events:

const int netlink_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (netlink_fd != -1)
{
    struct sockaddr_nl sa;

    memset(&sa, 0, sizeof(sa));
    sa.nl_family = AF_NETLINK;
    sa.nl_groups = RTNLGRP_LINK;
    bind(netlink_fd, (struct sockaddr*)&sa, sizeof(sa));
}

..And receive and handle messages however you want.

There is a library libnl for making that easier.

Upvotes: 8

Related Questions