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

avinash_ag1985 01-21-2009 05: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 02:12 PM

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

avinash_ag1985 01-28-2009 07: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 11: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-29-2009 12:18 AM

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 05:48 AM

do you have found working code sample?

jschiwal 11-16-2010 03: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 11:42 AM.