Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Linux: how can I programmatically determine if a NIC interface is enabled and plugged in?

I want to determine if a network card is enabled, up, and plugged in. Basically, I want to know if the network card will work. I need this information from with a C++ program, and would like to display an error message when the network isn't working properly. If possible I would like to avoid using shell commands to determine this information.

like image 579
Dylan Klomparens Avatar asked Jul 09 '10 20:07

Dylan Klomparens


5 Answers

  1. open AF_NETLINK socket
  2. bind it to sockaddr_nl with nl_groups = RTMGRP_LINK
  3. send message RTM_GETLINK to kernel
  4. make poll/epoll on socket to read RTM_NEWLINK and RTM_DELLINK messages
  5. you will receive initial interfaces list and its changes in future
like image 21
puchu Avatar answered Oct 21 '22 06:10

puchu


You can look at /sys/class/net/eth0/operstate where eth0 is your interface to see if it's up.

Look at /sys/class/net/eth0/carrier to see if there is a carrier.

Though I guess executing ifconfig and friends will give you more compatibility to *BSDs.

like image 130
EFraim Avatar answered Oct 21 '22 06:10

EFraim


Remember, on Linux "everything" is a file.

The best way would be to use the approved kernel<->userspace communication, namely sysfs, mounted at /sys. Network devices are linked at /sys/class/net

If you wish to use the ioctl interface, look at man netdevice

like image 4
Yann Ramin Avatar answered Oct 21 '22 06:10

Yann Ramin


How do you want to identify the network card? You might try taking a look at /etc/udev/rules.d/70-persistent-net.rules which maps hardware MAC addresses into nice names (like eth0).

Then, when you have the nicer name, you can run things like ethtool eth0 to determine if it is [physically] connected (last line), ifconfig eth0 to determine if it is up (look for "UP BROADCAST..."), and if it has an IP address.

I'm willing to guess there are automatic libraries for this though; have you looked around? I'm not sure if there's easily accessible code in NetworkManager, but that should be a good first place to look.

like image 1
gatoatigrado Avatar answered Oct 21 '22 07:10

gatoatigrado


Run through the output of getifaddrs, you can use the link layer for the MAC address to identify an adapter and check the ifa_flags for IFF_UP. Use AF_NETLINK for notifications about interface changes.

like image 1
Steve-o Avatar answered Oct 21 '22 07:10

Steve-o