i try to get the mac address of an interface i want to work with.
I use this code to do so, but i get always the error message "Inappropriate ioctl for device "
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.
#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.
Instead you need to use parentheses to avoid the operator precedence problem:
if((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) < 0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.