简体   繁体   English

原始套接字:不适当的ioctl

[英]raw socket: inappropriate ioctl

i try to get the mac address of an interface i want to work with. 我尝试获取要使用的接口的mac地址。

I use this code to do so, but i get always the error message "Inappropriate ioctl for device " 我使用此代码来执行此操作,但总是收到错误消息“设备的ioctl不正确”

I already tried using a different socket, ie AF_INET with SOCK_DGRAM (though i need the raw socket for later usage) without any difference. 我已经尝试使用其他套接字,即AF_INET和SOCK_DGRAM(尽管我需要原始套接字供以后使用)没有任何区别。

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if_ether.h>
#include <net/if.h>

int main()
{
    char if_name[] = "eth0";

    char mac[ETH_ALEN];
    struct ifreq ifr;
    int sock;

    if(sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)) < 0)
    {
        perror("SOCKET");
        return 1;
    }

    // get mac address of our interface
    memset(&ifr, 0, sizeof(struct ifreq));
    memcpy(ifr.ifr_name, if_name, 4);
    if(ioctl(sock, SIOCGIFHWADDR, &ifr) == -1)
    {
        perror("SIOCGIFHWADDR");
        return 1;
    }
    memcpy(mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
    printf("%x.%x.%x.%x.%x.%x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}

The problem should be pretty obvious if you turned on more warnings: 如果您打开更多警告,则问题应该非常明显:

if(sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)) < 0)

The above assigns the result of the comparison to sock , and of course it's not the valid socket. 上面将比较结果分配给sock ,当然,它不是有效的套接字。

Instead you need to use parentheses to avoid the operator precedence problem: 相反,您需要使用括号来避免运算符优先级问题:

if((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) < 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM