I'm hoping to get some feedback on code I wrote to retrieve the network interface link speed for the Linux OS.
in sigar build 1.6.4-0-g4b67f57 linux_sigar.c:1771
ifstat->speed = SIGAR_FIELD_NOTIMPL;
I'm proposing a function which can make a system call to ioctrl to retrieve this information from the device drivers. I'm hoping that if this code could be included in future builds if it proves reliable and consistent. Here is the code I have written and tested to retrieve this information:
/**
* Author: Justin Allen (jallen (AT)ucsd.edu)
* Date: 6/18/2010
* This code is provided on an "as is" basis, with no conditions or warranties, either expressed or implied.
* Prototype program to get the network link speed of a network interface by making a system call to ioctrl to query the driver
*/
#include < stdio.h >
#include < sys/socket.h >
#include < sys/ioctl.h >
#include < netinet/in.h >
#include < linux/sockios.h >
#include < linux/if.h >
#include < linux/ethtool.h >
#include < string.h >
#include < stdlib.h >
long get_link_speed(const char* interface)
{
int sock, rc;
struct ifreq ifr;
struct ethtool_cmd edata;
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock<0) {
perror("socket");
return -1;
}
strncpy(ifr.ifr_name, interface , sizeof(ifr.ifr_name));
ifr.ifr_data = &edata;
edata.cmd = ETHTOOL_GSET;
rc = ioctl(sock, SIOCETHTOOL, &ifr);
if (rc<0) {
perror("ioctl");
return -1;
}
switch (edata.speed) {
case SPEED_10: return (edata.speed * 1000000); break; // 10Mbps
case SPEED_100: return (edata.speed * 1000000); break; //100Mbps
case SPEED_1000: return (edata.speed * 1000000000); break; // 1Gbps
case SPEED_2500: return (edata.speed * 1000000000); break; // 2.5Gbps
case SPEED_10000: return (edata.speed * 1000000000); break; // 10Gbps
default: return (edata.speed);
}
return (edata.speed);
}
int main (int argc, char **argv)
{
fprintf(stdout, "speed: %d\n", get_link_speed("eth0"));
return 0;
}
Message was edited by: jrallen9
Message was edited by: jrallen9
Message was edited by: jrallen9
Message was edited by: jrallen9