Chinaunix首页 | 论坛 | 博客
  • 博客访问: 255789
  • 博文数量: 99
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 246
  • 用 户 组: 普通用户
  • 注册时间: 2013-05-03 18:23
个人简介

qrasvasdf

文章分类

全部博文(99)

文章存档

2016年(1)

2015年(36)

2014年(62)

我的朋友

分类: LINUX

2014-10-16 14:44:05


点击(此处)折叠或打开

  1. #include <sys/ioctl.h>

  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <net/if.h>
  5. #include <arpa/inet.h>
  6. #include <unistd.h>
  7. #include <stdio.h>
  8. #define MAX_IFS 64
  9. int main(int argc, char **argv) {
  10.     struct ifreq *ifr, *ifend;
  11.     struct ifreq ifreq;
  12.     struct ifconf ifc;
  13.     struct ifreq ifs[MAX_IFS];
  14.     int SockFD;
  15.     SockFD = socket(AF_INET, SOCK_DGRAM, 0);
  16.     ifc.ifc_len = sizeof(ifs);
  17.     ifc.ifc_req = ifs;
  18.     if (ioctl(SockFD, SIOCGIFCONF, &ifc) < 0) {
  19.         printf("ioctl(SIOCGIFCONF): %m/n");
  20.         return 0;
  21.     }
  22.     ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
  23.     for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
  24.         if (ifr->ifr_addr.sa_family == AF_INET) {
  25.             strncpy(ifreq.ifr_name, ifr->ifr_name,sizeof(ifreq.ifr_name));
  26.             if (ioctl (SockFD, SIOCGIFHWADDR, &ifreq) < 0) {
  27.                 printf("SIOCGIFHWADDR(%s): %m/n", ifreq.ifr_name);
  28.                 return 0;
  29.             }
  30.             printf("Ip Address %s/n", inet_ntoa( ( (struct sockaddr_in *) &ifr->ifr_addr)->sin_addr));
  31.             printf("Device %s -> Ethernet %02x:%02x:%02x:%02x:%02x:%02x/n", ifreq.ifr_name,
  32.                     (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[0],
  33.                     (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[1],
  34.                     (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[2],
  35.                     (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[3],
  36.                     (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[4],
  37.                     (int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[5]);
  38.         }
  39.     }
  40.     return 0;
  41. }

注:因为SIOCGIFCONF只能获取IP层的配置,当网卡没有设置IP,它就获取不到网卡信息
阅读(4963) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~