2

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.

2
  • Please provide some code that shows that you at least tried to do something. Also post any errors, if any. Help us help you. Commented Jun 20, 2018 at 8:08
  • Which version of Ubuntu? It matters. Commented Jun 20, 2018 at 10:02

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.