Question

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]);
}
Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top