Skip to content

Instantly share code, notes, and snippets.

@rongyi
Created July 29, 2013 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rongyi/6101910 to your computer and use it in GitHub Desktop.
Save rongyi/6101910 to your computer and use it in GitHub Desktop.
get iface index
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/ethtool.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <string.h>
#include <errno.h>
static int iface_get_id(const char *device)
{
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
int fd = socket(PF_PACKET, SOCK_DGRAM, 0);
if (fd == -1) {
perror("get raw socket fail");
return -1;
}
if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
perror("ioctl SIOCGIFINDEX fail");
return -1;
}
return ifr.ifr_ifindex;
}
int main()
{
const char *device = "eth0";
int dev_id = iface_get_id(device);
if (dev_id == -1) {
fprintf(stderr, "fail to get index\n");
} else {
printf("device %s's index is %d'\n", device, dev_id);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment