How to Get Interface Name List

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);
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值