Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Linux by (5k points)

Right now, all of the answers mentioned getting the MAC address always use eth0. But if somehow, instead of eth0, my interfaces start with eth1, what will happen in that case? Also on OS X the interface names are different.

Also, the interface eth0 may be present but is unused. i.e. not active, it doesn't have an IP.

Kindly help me out with finding out the MAC address for the first available active interface.

eth0   Link encap:Ethernet  HWaddr <some addr>

          inet6 addr: <some addr> Scope:Link

          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:123

          RX packets:123 errors:123 dropped:123 overruns:123 frame:123

          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123

          collisions:123 txqueuelen:123 

          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)

          Interrupt:123 Memory:00000000-00000000

eth1      Link encap:Ethernet  HWaddr <some addr>

          inet addr:<some addr>  Bcast:<some addr>  Mask:<some addr>

          inet6 addr: <some addr> Scope:Link

          UP BROADCAST RUNNING MULTICAST  MTU:123 Metric:123

          RX packets:123 errors:123 dropped:123 overruns:123 frame:123

          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123

          collisions:123 txqueuelen:123 

          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)

          Interrupt:123 Memory:00000000-00000000

1 Answer

0 votes
by (10.2k points)

In Linux, it is pretty simple to find out the MAC address.

If you analyze properly, the interface name and the first and last fields on a line containing no leading whitespace.

But If any one of the indented lines has inet addr: the latest interface name and MAC address should be printed.

ifconfig -a | 

awk '/^[a-z]/ { iface=$1; mac=$NF; next } 

/inet addr:/ { print iface, mac }'

You should note it down that multiple interfaces can meet your criteria. Then, the multiple lines will be printed by scripts. If you only want to print the first match, add; exit right before the final closing brace.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 26, 2021 in Linux by sheela_singh (9.5k points)
0 votes
1 answer

Browse Categories

...