How to get MAC address of your machine using a C program?

Bruce picture Bruce · Nov 22, 2009 · Viewed 144.6k times · Source

I am working on Ubuntu. How can I get MAC address of my machine or an interface say eth0 using C program.

Answer

user175104 picture user175104 · Nov 23, 2009

Much nicer than all this socket or shell madness is simply using sysfs for this:

the file /sys/class/net/eth0/address carries your mac adress as simple string you can read with fopen()/fscanf()/fclose(). Nothing easier than that.

And if you want to support other network interfaces than eth0 (and you probably want), then simply use opendir()/readdir()/closedir() on /sys/class/net/.