-   Linux - Networking (
-   -   How to get link state of interface (

avinash_ag1985 01-21-2009 04:10 AM

How to get link state of interface
How do I get the link state (whether cable is plugged in or not) of an ethernet interface? Is it enough to query the IFF_RUNNING flag in if_flags field of ifreq structure, via a SIOCGIFFLAGS ioctl, or is something more required.

(BTW, I already tried the ioctl method, with no luck. Below is the code I used.)

int retVal;
struct ifreq ifr;
retVal = ioctl(sockData->sockInt, SIOCGIFFLAGS, &ifr);
if (retVal < 0)
debug_printf(DEBUG_NORMAL, "Interface %s not found!\n", ctx->intName);
return FALSE;

if (((ifr.ifr_flags & IFF_UP) == IFF_UP) && ((ifr.ifr_flags & IFF_RUNNING) == IFF_RUNNING))
return TRUE;
} else {
SET_FLAG(ctx->flags, WAS_DOWN);
return FALSE;

Any ideas, guys?

Tinkster 01-22-2009 01:12 PM

I'd be looking at the source of ethtool and see how they do it ;}

avinash_ag1985 01-28-2009 06:19 AM

Thanks Tinkster. Tried it but no dice. Its using the netif_carrier_ok function, which I think cannot be used in userspace. Further on the netif_carrier_ok function tests the flag (or macro) __LINK_STATE_NOCARRIER, from a set of flags contained in net_device structure, which, again, cannot be used from userspace (I think ;)). Do correct me if I'm wrong.

Any other ideas, dude? Thanks in advance

JulianTosh 01-28-2009 10:48 AM

Save as (and make executable, chmod 775

ifconfig $1 | egrep 'UP |DOWN ' | sed "s/\s*\(\w*\)\s*.*/$1: \1/"
Usage: eth?

Example: eth0

eth0: UP

avinash_ag1985 01-28-2009 11:18 PM

Perhaps i need to make myself clearer. I have to do this via a C program ONLY, no scripts allowed.

Another thing. I am doing this as part of running xsupplicant (open source Linux version). I notice that the the IFF_RUNNING flag is updated properly each time before I run xsupplicant. However, after I simply run xsupplicant once, the flag is no longer updated. Wierd.

Any ideas guys?

klsc 11-16-2010 04:48 AM

do you have found working code sample?

jschiwal 11-16-2010 02:52 PM

klsc: Please look at the date of the last post to prevent resurrecting a thread that is almost two years old.

All times are GMT -5. The time now is 01:17 AM.