Welcome

Wheresoever you go, go with all your heart. (Confucius)

5/14/2013

Getting MAC address on the linux by using C++


After getting a list of network interfaces,
This code will print MAC address per each interface except loopback.

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

#define MAC_STRING_LENGTH 13

int main()
{
    char mac_address[MAC_STRING_LENGTH];

    struct ifreq ifr;
    struct ifconf ifc;
    char buf[1024];
    int success = 0;

    int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock == -1) { return -1;}

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    if (ioctl(sock, SIOCGIFCONF, &ifc) == -1)
    {
        std::cout << "error" << std::endl;
        return 0;
    }

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

    for (; it != end; ++it) {
        std::cout << it->ifr_name << std::endl;

        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) {

                    for (int i = 0; i < 6; ++i)
                        snprintf(mac_address+i*2,MAC_STRING_LENGTH-i*2,"%02x",(unsigned char) ifr.ifr_addr.sa_data[i]);
                        std::cout << mac_address << std::endl;

                }
            }
        }
        else {
            std::cout << "error" << std::endl;
            return 0;
        }
    }
}

No comments: