ioctl()函数获取本机IP、MAC

#include <sys/ioctl.h>
int ioctl(int d, int request, ...);
/* Socket configuration controls. */
#define SIOCGIFADDR 0x8915    /* get PA address */
#define SIOCSIFADDR 0x8916    /* set PA address */
#define SIOCGIFHWADDR 0x8927  /* Get hardware address */
struct ifreq,Interface request structure,在头文件<net/if.h>

 

[cpp] view plaincopy
 
  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3. #include <sys/socket.h>  
  4. #include <arpa/inet.h>  
  5. #include <string.h>  
  6. #include <sys/ioctl.h>  
  7. #include <net/if.h>  
  8.   
  9. int main()  
  10. {  
  11.     int sock;  
  12.     int res;  
  13.     struct ifreq ifr;  
  14.   
  15.     sock = socket(AF_INET, SOCK_STREAM, 0);  
  16.     strcpy(ifr.ifr_name, "eth0");  
  17.     res = ioctl(sock, SIOCGIFADDR, &ifr);  
  18.   
  19.     printf("IP: %s\n",inet_ntoa(((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr));  
  20.   
  21.     strcpy(ifr.ifr_name, "eth0");  
  22.     res = ioctl(sock, SIOCGIFHWADDR, &ifr);  
  23.   
  24.     int i;  
  25.     char mac[32];  
  26.     for(i = 0; i < 6; ++i)  
  27.     {  
  28.         sprintf(mac + 3*i, "%02x:", (unsigned char)ifr.ifr_hwaddr.sa_data[i]);  
  29.     }  
  30.     printf("MAC: %s\n",mac);  
  31.   
  32.     return 0;  
  33. }  
  34. ifreq结构定义在/usr/include/net/if.h,用来配置ip地址,激活接口,配置MTU等接口信息的。
    其中包含了一个接口的名字和具体内容——(是个共用体,有可能是IP地址,广播地址,子网掩码,MAC号,MTU或其他内容)。
    ifreq包含在ifconf结构中。而ifconf结构通常是用来保存所有接口的信息的。
posted @ 2015-11-12 16:54  周人假的  阅读(2122)  评论(0编辑  收藏  举报