How to check if interface is up
Solution 1
Answer was simple: I used the bitwise OR (|
) operator instead of the AND (&
) operator. Fixed code is:
bool is_interface_online(std::string interface) {
struct ifreq ifr;
int sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, interface.c_str());
if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
perror("SIOCGIFFLAGS");
}
close(sock);
return !!(ifr.ifr_flags & IFF_UP);
}
Solution 2
If you care about the up/down state of the interface you might want to use the "IFF_RUNNING" flag instead of the "IFF_UP" flag provided by the current answer.
Solution 3
Have you considered using the strace
command to see how ifconfig
works? you can even see what parameters are passed to functions and other interesting details of how ifconfig
works ..
MiJyn
Updated on June 14, 2022Comments
-
MiJyn about 2 years
Title pretty much says it all. If I run
ifconfig
, I get this:eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet -snip- netmask 255.255.255.0 broadcast -snip- ...
Using this, I can know if it's up or not (
<UP,...
), but I want to be able to do this in C (or C++, if there is a simpler solution there) without relying on parsing external processes.
Here is what I've got so far (doesn't work):
bool is_interface_online(std::string interface) { struct ifreq ifr; int sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP); memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, interface.c_str()); if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { perror("SIOCGIFFLAGS"); } close(sock); return !!(ifr.ifr_flags | IFF_UP); }
Can anyone point me in the correct direction for this?
-
MiJyn about 11 yearsYes I have, in fact, that's what I used to write the function :D
-
David Pickup about 5 yearsI know this is an extremely old post, but what's the purpose of the
!!
in the return statement? I'm not aware of a!!
operator, so is this simply "not not"? If so, then the!!
can be removed. -
Aodren BARY almost 5 yearsa little late answer but the purpose of two
!!
is simple. It's use to return 0 or 1 from large return exit code. Exemple!! 0
will return 0 because!0 = 1
and!1 = 0
. But for any other valuesn != 0
, it will return1
. Exemple with!!10
:!10 = 0
and!0 = 1
-
Brijesh Valera over 4 yearsCan I use the same in virtual environment? How can I set interface down in virtual environment? I am running test program which checks IFF_RUNNING flag at every 500 milliseconds. I am not receiving interface down, it always finds IFF_RUNNING flag set. Need help in this matter.