Created
July 29, 2013 02:59
-
-
Save rongyi/6101910 to your computer and use it in GitHub Desktop.
get iface index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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