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

  

转载于:https://www.cnblogs.com/Flychown/p/6441857.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值