I'm trying to retrieve the emac link status, speed, and duplex in C code. I know I can make a system call to "cat /proc/emac_link" and parse the output. But is there a better way to get this information, say, through a driver IOCTL?
Thanks
This thread has been locked.
If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.
I'm trying to retrieve the emac link status, speed, and duplex in C code. I know I can make a system call to "cat /proc/emac_link" and parse the output. But is there a better way to get this information, say, through a driver IOCTL?
Thanks
#include <errno.h>
#include <linux/ethtool.h>
#include <linux/sockios.h>
#include <net/if.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
int main ( int argc, char **argv )
{
struct ifreq ifr;
int sock = socket ( AF_INET, SOCK_DGRAM, 0 );
struct ethtool_cmd edata;
char ifname[32];
int result;
strcpy ( ifname, "eth0" );
strncpy ( ifr.ifr_name, ifname, sizeof ( ifr.ifr_name ));
ifr.ifr_addr.sa_family = AF_INET;
result = ioctl ( sock, SIOCGIFFLAGS, &ifr );
if ( result == 0 ) {
// successfully got the flags
if ( ifr.ifr_flags | IFF_UP ) {
printf ( "Ethernet interface is up\n" );
}
else {
printf ( "Ethernet interface is down\n" );
}
}
else {
printf ( "%s: Error getting ethernet flags. %s (%d)\n",
__FUNCTION__,
strerror ( errno ),
errno );
}
ifr.ifr_data = (char *) &edata;
edata.cmd = ETHTOOL_GSET;
result = ioctl ( sock, SIOCETHTOOL, &ifr );
if ( result == 0 ) {
switch ( edata.speed ) {
case SPEED_10:
printf ( "Speed is 10Mbps\n" );
break;
case SPEED_100:
printf ( "Speed is 100Mbps\n" );
break;
case SPEED_1000:
printf ( "Speed is 1Gbps\n" );
break;
case SPEED_10000:
printf ( "Speed is 10Gbps\n" );
break;
default:
printf ( "Speed (%d) is unknown\n", edata.speed );
break;
}
if ( edata.duplex == DUPLEX_HALF ){
printf ( "Half duplex\n" );
}
else {
printf ( "Full duplex\n" );
}
}
else {
printf ( "%s: Error getting ethernet info. %s (%d)\n",
__FUNCTION__,
strerror ( errno ),
errno );
}
return 0;
}