raw socket:不合适的ioctl

Hor*_*tor 1 c sockets linux ioctl

我试图获取我想要使用的接口的mac地址.

我使用此代码这样做,但我总是收到错误消息"不适当的设备ioctl"

我已经尝试使用不同的套接字,即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]);
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 6

如果您打开更多警告,问题应该非常明显:

if(sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)) < 0)
Run Code Online (Sandbox Code Playgroud)

以上分配的结果进行比较sock,当然这不是有效的套接字.

相反,您需要使用括号来避免运算符优先级问题:

if((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) < 0)
Run Code Online (Sandbox Code Playgroud)