C program to read mac address using WiFi interface name

If you need to get the mac address of certain wifi interface using C program, you can use the below program. This program should work on any Linux as well as Android platforms.

$ vim read_wifi_mac.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// here our wifi interface was shown as wlp3s0, in your case it may be
// wlan0 , hence you need to use /sys/class/net/wlan0/address instead
// of /sys/class/net/wlp3s0/address

char *read_mac_address() {
        char *t_mac = (char *) malloc(32);
        char *mac = (char *) malloc(32);
        FILE *fp = NULL;

        fp = popen("cat /sys/class/net/wlp3s0/address", "r");
        if (fp == NULL) {
                printf("Failed to get mac address using command\n" );
                return NULL;

        fgets(t_mac, 32, fp);
        strncpy(mac, t_mac, strlen(t_mac) - 1); //remove /n from mac read

        return mac;

int main(int argc, char **argv) {
        char *mac = NULL;
        mac = read_mac_address();
        printf("%s\n", mac);

Now, you can compile and run the program as,

 $ gcc -o read_wifi_mac read_wifi_mac.c 
 $ ./read_wifi_mac 
Follow Lynxbee

Leave a Reply / Ask Question