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

前端 未结 5 1055
旧巷少年郎
旧巷少年郎 2021-02-05 11:51

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, a

5条回答
  •  滥情空心
    2021-02-05 12:02

    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.

提交回复
热议问题