Best way to extract MAC address from ifconfig'

2019-01-21 04:28发布

What is the best way to extract the MAC address from ifconfig's output?

Sample output:

bash-3.00# ifconfig eth0        
eth0      Link encap:Ethernet  HWaddr 1F:2E:19:10:3B:52    
          inet addr:127.0.0.66  Bcast:127.255.255.255  Mask:255.0.0.0    
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          ....
          ....

Should I use cut, AWK or anything else, and what are the merits and demerits of one method over the other.

17条回答
2楼-- · 2019-01-21 05:11

On Ubuntu 14.04 in terminal

ifconfig | grep HW
查看更多
Lonely孤独者°
3楼-- · 2019-01-21 05:11

Note: on OS X eth0 may not work. Use p2p0:

ifconfig p2p0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
查看更多
甜甜的少女心
4楼-- · 2019-01-21 05:12

I prefer the method described here (with slight modification): http://www.askdavetaylor.com/how_do_i_figure_out_my_ip_address_on_a_mac.html

ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d " " -f2

Which you can then alias to a short 'myip' command for future use:

echo "alias myip=\"ifconfig | grep 'inet ' | grep -v 127.0.0.1 | cut -d ' ' -f2\"" >> ~/.bash_profile
查看更多
forever°为你锁心
5楼-- · 2019-01-21 05:12

ifconfig en0 | grep ether - for wired mac address

ifconfig en1 | grep ether - for wireless mac address

查看更多
看我几分像从前
6楼-- · 2019-01-21 05:13

Output of ifconfig:

$ifconfig

eth0      Link encap:Ethernet  HWaddr 00:1b:fc:72:84:12
      inet addr:172.16.1.13  Bcast:172.16.1.255  Mask:255.255.255.0
      inet6 addr: fe80::21b:fcff:fe72:8412/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:638661 errors:0 dropped:20 overruns:0 frame:0
      TX packets:93858 errors:0 dropped:0 overruns:0 carrier:2
      collisions:0 txqueuelen:1000
      RX bytes:101655955 (101.6 MB)  TX bytes:42802760 (42.8 MB)
      Memory:dffc0000-e0000000

lo        Link encap:Local Loopback
      inet addr:127.0.0.1  Mask:255.0.0.0
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING  MTU:16436  Metric:1
      RX packets:3796 errors:0 dropped:0 overruns:0 frame:0
      TX packets:3796 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0
      RX bytes:517624 (517.6 KB)  TX bytes:517624 (517.6 KB)

The best way to extract MAC address is:

ifconfig | sed '1,1!d' | sed 's/.*HWaddr //' | sed 's/\ .*//' | sed -e 's/:/-/g' > mac_address
查看更多
Viruses.
7楼-- · 2019-01-21 05:14

I would use:

ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'

The -o will cause grep to only print the part of the line that matches the expression. [[:xdigit:]]{1,2} will match 1 or 2 hexidecimal digits (Solaris doesn't output leading zeros).

查看更多
登录 后发表回答