Linux系统的网络接口列表可以通过两种方式获得: 解析/proc/net/dev文件, 或者通过ioctl的SIOCGIFCONF命令。ioctl只支持AF_INET套接字,并且通过ioctl只能获得已经启动并且已经分配了IP地址的接口,而从/proc/net/dev可以获得所有的网络接口。
#include <sys/types.h> #include &li;sys/ioctl.h> #include &li;sys/socket.h> #include &li&netinet/in.h> #include <net/if.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #define IF_MAX 30 #define LINE_MAX 512 #define PATH_PROC_NET_DEV "/proc/net/dev" int main(int argc, char *argv[]) { FILE * fp; char line[LINE_MAX]; struct ifconf ifc; int numreqs = 10; int fd; int i; struct ifreq * ifr = NULL; if(!(fp = fopen(PATH_PROC_NET_DEV, "r"))) { perror("fopen"); exit(1); } // Skip first two lines fgets(line, sizeof(line), fp); fgets(line, sizeof(line), fp); printf("Interfaces in the system (by %s):/n", PATH_PROC_NET_DEV); printf("--------------------------------------------------/n"); while(fgets(line, sizeof(line), fp)) { char * pc; i = 0; // Truncate the line at char ':' if((pc = strchr(line, ':'))) { *pc = '/0'; pc = line; // Skip the spaces ahead while(*pc == ' ') pc++; // now we got the interface name printf("%s/n", pc); } } fclose(fp); if((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); exit(1); } ifc.ifc_len = sizeof(struct ifreq) * numreqs; ifc.ifc_buf = malloc(ifc.ifc_len); memset(ifc.ifc_buf, 0, ifc.ifc_len); if(ioctl(fd, SIOCGIFCONF, &ifc) != 0) { perror("SIOCGIFCONF"); free(ifc.ifc_buf); close(fd); exit(1); } close(fd); if(ifc.ifc_len == sizeof(struct ifreq) * numreqs) printf("The system has at least %d interfaces, " "please increase the buffer./n", numreqs); ifr = ifc.ifc_req; printf("Interfaces in the system (by SIOCGIFCONF):/n"); printf("--------------------------------------------------/n"); for(i=0; i<ifc.ifc_len; i+=sizeof(struct ifreq)) { printf("%s/n", ifr->ifr_name); ifr++; } free(ifc.ifc_buf); exit(0); }