ioctrl 获取本机IP及MAC地址

通过使用ioctl可以获得本机的一些信息,这里记录获得interface IP及MAC的过程。

1:ioctl 函数的作用是什么

man ioctl:

DESCRIPTION
The ioctl() function manipulates the underlying device parameters of special files. In particular, many operating characteris‐
tics of character special files (e.g., terminals) may be controlled with ioctl() requests. The argument fd must be an open file
descriptor.

The second argument is a device-dependent request code. The third argument is an untyped pointer to memory. It's traditionally
char *argp (from the days before void * was valid C), and will be so named for this discussion.

An ioctl() request has encoded in it whether the argument is an in parameter or out parameter, and the size of the argument argp
in bytes. Macros and defines used in specifying an ioctl() request are located in the file <sys/ioctl.h>.

2:测试例子

/*
    用socket获得当前interface的信息
    1:ip地址
    2:mac地址
    3:interface index
注:创建的是原始套接字,编译及执行都需要root权限
*/
int read_interface(const char* interface)
{
    int fd;
    int ret = 0;
    struct ifreq ifr;
    struct sockaddr_in *ip_addr = NULL;
    char mac[6] = {0};
    memset(&ifr, 0, sizeof(struct ifreq));
    fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    if (fd > 0){
        ifr.ifr_addr.sa_family = AF_INET;
        strcpy(ifr.ifr_name, interface);

        //get interface ip
        if(ioctl(fd, SIOCGIFADDR, &ifr) == 0){
            ip_addr = (struct sockaddr_in *)&ifr.ifr_addr;
            printf("The %s ip addr is %s\n",ifr.ifr_name,inet_ntoa(ip_addr->sin_addr));
        } else {
            printf("SIOCGIFADDR failed, error:%s\n", strerror(errno));
            ret = -1;
            goto out;
        }

        //get interface mac
        if(ioctl(fd, SIOCGIFHWADDR, &ifr) == 0){
            memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
            printf("interface mac: %02X:%02X:%02X:%02X:%02X:%02X\n",
                mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);            
        } else {
            printf("SIOCGIFHWADDR failed, error:%s\n", strerror(errno));
            ret = -1;
            goto out;
        }

        //get interface index
        if (ioctl(fd, SIOCGIFINDEX, &ifr) == 0) {
            printf("The interface index:%d\n",ifr.ifr_ifindex);
        } else {
            printf("SIOCGIFINDEX failed, error:%s\n", strerror(errno));
            ret = -1;
            goto out;
        }
    } else {
        printf("%s\n",strerror(errno));
        ret = -1;
    }
out:
    close(fd);
    return ret;
}

3:ioctl的第二个参数有很多,了解它们可以在需要时使用

参考:http://blog.csdn.net/evenness/article/details/7665970

  

posted @ 2017-02-25 15:04  会飞的小丑  阅读(960)  评论(0编辑  收藏  举报