zoukankan      html  css  js  c++  java
  • 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 ",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 ",mac);  
    31.   
    32.     return 0;  
    33. }  
    34. ifreq结构定义在/usr/include/net/if.h,用来配置ip地址,激活接口,配置MTU等接口信息的。
      其中包含了一个接口的名字和具体内容——(是个共用体,有可能是IP地址,广播地址,子网掩码,MAC号,MTU或其他内容)。
      ifreq包含在ifconf结构中。而ifconf结构通常是用来保存所有接口的信息的。
  • 相关阅读:
    关于字符串转义的代码
    JAVA发布aar文件
    apache虚拟主机配置HTTPS
    font-face跨域办法
    Javascript数组方法(译)
    Python动态生成变量
    给AOP的after函数使用原函数局部变量
    stopImmediatePropagation的应用
    IE9或以上的浏览器flash值为空时,导致domready不触发
    html写法对gzip压缩率的影响
  • 原文地址:https://www.cnblogs.com/zhouhbing/p/4959545.html
Copyright © 2011-2022 走看看