我尝试获取我想要使用的接口(interface)的 mac 地址。
我使用这段代码来这样做,但我总是收到错误消息“Inappropriate ioctl for device "
我已经尝试使用不同的套接字,即 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]);
}
最佳答案
如果您打开更多警告,问题应该会很明显:
if(sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)) < 0)
上面将比较的结果赋值给sock
,当然这不是有效的socket。
相反,您需要使用括号来避免 operator precedence问题:
if((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) < 0)
关于c - 原始套接字 : inappropriate ioctl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17993476/