Can't get mac address with ioctl on Linux when disconnected from Wifi

Go To StackoverFlow.com

1

I'm getting a mac address using this method:

#include <sys/ioctl.h>
#include <net/if.h> 
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>

int main()
{
    ifreq ifr;
    ifconf ifc;
    char buf[1024];
    int success = 0;

    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock == -1) { /* handle error*/ };

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */ }

    ifreq* it = ifc.ifc_req;
    const ifreq* const end = it + (ifc.ifc_len / sizeof(ifreq));

    for (; it != end; ++it) {
        strcpy(ifr.ifr_name, it->ifr_name);
        if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
            if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
                if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
                    success = 1;
                    break;
                }
            }
        }
    }

    unsigned char mac_address[6];

    if (success) memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
}

(Taken from How to get MAC address of your machine using a C program?)

However, when I disconnect from the Wifi Network, the first call to ioctl returns an empty list.

Could you explain this behavior?

2012-04-03 20:22
by Butaca
Any reason for not using rtnetlink instead ? Also, SIOCGIFCONF only returns interfaces that are 1) up and running and 2) have an ipv4 address - BatchyX 2012-04-03 20:40
Have you tried this solution - Karl Bielefeldt 2012-04-03 20:49
Thanks guys. I'm new to linux programming. I read the documentation at kernel.org but I missed the part that SIOCGIFCONF returns only up and running interfaces. I need to get a mac address of the first interface, regardless if it is running or not. Which flags should I use? I'll try Karl suggestion tomorrow at work though - Butaca 2012-04-03 23:52


1

The described behavior is due to the fact that SIOCGIFCONF returns interfaces that are up and running.

Credit goes to Batchy

2012-04-09 17:01
by Butaca