Skip to content

Instantly share code, notes, and snippets.

@kk1fff
Created June 12, 2013 17:30
Show Gist options
  • Save kk1fff/5767390 to your computer and use it in GitHub Desktop.
Save kk1fff/5767390 to your computer and use it in GitHub Desktop.
Getting information of network interface in linux
#include <linux/types.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/kernel.h>
#include <linux/wireless.h>
#include <linux/sockios.h>
#include <linux/ethtool.h>
#include <string.h>
#include <stdio.h>
int main() {
int s = socket(AF_INET, SOCK_DGRAM, 0);
struct ifconf ifc;
int len = 100 * sizeof(struct ifreq);
char buf[len];
int e;
int interface_count;
char *ptr;
ifc.ifc_len = len;
ifc.ifc_buf = buf;
e = ioctl(s, SIOCGIFCONF, &ifc);
interface_count = ifc.ifc_len;
ptr = ifc.ifc_buf;
// Iterate over interfaces.
while (interface_count > 0) {
struct ifreq* ifr = (struct ifreq *)ptr;
struct ifreq ifr1 = *ifr;
struct iwreq wrq;
struct ethtool_cmd ecmd;
int si = sizeof(struct ifreq);
e = ioctl(s, SIOCGIFADDR, &ifr1);
printf("Interface: %s\n", ifr1.ifr_name);
// Get ethtool information.
ecmd.cmd = ETHTOOL_GSET;
ifr->ifr_data = (caddr_t)&ecmd;
e = ioctl(s, SIOCETHTOOL, ifr);
// Print ethtool information if available.
if (e == -1) {
printf(" [ethtool] cannot get ethtool\n");
} else {
printf(" [ethtool] speed: %d\n", (ecmd.speed_hi << 16) | ecmd.speed);
}
// Get wireless extension.
strcpy(wrq.ifr_name, ifr1.ifr_name);
e = ioctl(s, SIOCGIWRATE, &wrq);
if (e == -1) {
printf(" [iwext] cannot get wireless extension\n");
} else {
printf(" [iwext] speed: %d\n", wrq.u.bitrate.value);
}
interface_count -= si;
ptr += si;
}
close(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment