Get network interface’s MAC address and IP address

#include <iostream>
#include <cstring>
#include <cstdio>
#include <inttypes.h>
#include <ifaddrs.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

using namespace std;

void get_mac_addrs( )
{
    /// get interface addresses
    struct ifaddrs* interface_addrs  = NULL;
    if( getifaddrs( &interface_addrs  ) == -1 )
    {
        return;
    }

    if( !interface_addrs )
    {
        return;
    }

    int32_t sd = socket( PF_INET, SOCK_DGRAM, 0 );
    if( sd < 0 )
    {
        /// free memory allocated by getifaddrs
        freeifaddrs( interface_addrs );
        return;
    }

    /// get MAC address for each interface
    for( struct ifaddrs* ifa = interface_addrs; ifa != NULL; ifa = ifa->ifa_next )
    {
        /// print MAC address
        if( ifa->ifa_data != 0 )
        {
            struct ifreq req;
            strcpy( req.ifr_name, ifa->ifa_name );
            if( ioctl( sd, SIOCGIFHWADDR, &req ) != -1 )
            {
                uint8_t* mac = (uint8_t*)req.ifr_ifru.ifru_hwaddr.sa_data;
                printf( "%s:MAC[%02X:%02X:%02X:%02X:%02X:%02X]\n",
                        ifa->ifa_name,
                        mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] );
            }
        }

        /// print IP address
        if( ifa->ifa_addr != 0 )
        {
            int family = ifa->ifa_addr->sa_family;
            if( family == AF_INET || family == AF_INET6 )
            {
                char host[NI_MAXHOST];
                if( getnameinfo( ifa->ifa_addr,
                                 (family == AF_INET)? sizeof( struct sockaddr_in ) : sizeof( struct sockaddr_in6 ),
                                 host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST ) == 0 )
                {
                    printf( "%s:Address Family:[%d%s]:IP[%s]\n",
                            ifa->ifa_name,
                            family,
                            (family == AF_PACKET) ? " (AF_PACKET)" :
                            (family == AF_INET) ?   " (AF_INET)" :
                            (family == AF_INET6) ?  " (AF_INET6)" : "",
                            host );
                }
            }
        }
    }

    /// close socket
    close( sd );

    /// free memory allocated by getifaddrs
    freeifaddrs( interface_addrs );
}

int main()
{
    cout << "Localhost's MAC address:\n";

    get_mac_addrs();

    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s