Here is a short example of how to get the mac address of a network interface in linux from a c program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include <net/if.h>

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>

int main(int argc, char **argv) {
        int sock = socket(PF_INET, SOCK_DGRAM, 0);
        struct ifreq req;
        int i = 0;

        if (argc < 2) {
                fprintf(stderr, "Usage: %s <interfacename>\n", argv[0]);
                exit(EXIT_FAILURE);
        }

        if (sock < 0) {
                perror("socket");
                exit(EXIT_FAILURE);
        }

        memset(&req, 0, sizeof(req));
        strncpy(req.ifr_name, argv[1], IF_NAMESIZE - 1);

        if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
                perror("ioctl");
                exit(EXIT_FAILURE);
        }

        for(i=0;i<6;i++) {
                printf("%.2X", (unsigned char) req.ifr_hwaddr.sa_data[i]);
                if (i < 5)
                        printf(":");
        }
        printf("\n");

        close(sock);

        exit(EXIT_SUCCESS);
        return 0;
}




Last Modified: 21 February 2017

Releated Posts


2017-03-01 - Shooting yourself in the head with threads
2013-02-16 - C - Some simple examples of using strcat
2012-11-03 - C - How to override malloc / free
2012-09-22 - Linux Programming - Using inotify for detecting file modifications
2012-08-09 - C++ - Check an IP Address is in a IP Mask
2012-06-16 - CPP - Using gperf
2012-04-05 - Using gdb to debug a core file
2012-03-15 - C - Is the stdin a tty
2012-03-13 - C - Converting from char / string to int using atoi
2012-03-08 - C - UDP Socket example
2012-02-20 - C - Get home dir location in linux
2012-02-17 - C - IP address validation
2012-02-15 - C - Get current ip address of an interface
2012-02-10 - Using asprintf instead of sprintf or snprintf
2012-01-31 - C - Example of how to overwrite argv
2012-01-30 - C - The string reverse
2012-01-27 - C - Palindrome
2012-01-26 - C - Example of using popen
2011-12-28 - C - gethostbyname example
2011-12-11 - C - Linux get mac address from interface
2011-02-10 - CSharp - Wake on Lan (WOL) Packet