Best way to extract MAC address from ifconfig's output?

前端 未结 19 1651
面向向阳花
面向向阳花 2020-12-12 15:31

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

Sample output:

bash-3.00# ifconfig eth0        
eth0      Link          


        
相关标签:
19条回答
  • 2020-12-12 16:10

    You can do a cat under /sys/class/

    cat /sys/class/net/*/address
    

    Specifically for eth0

    cat /sys/class/net/eth0/address
    
    0 讨论(0)
  • 2020-12-12 16:10

    How about this one:

    ifconfig eth0 | grep -Eo ..\(\:..\){5}
    

    or more specifically

    ifconfig eth0 | grep -Eo [:0-9A-F:]{2}\(\:[:0-9A-F:]{2}\){5}
    

    and also a simple one

    ifconfig eth0 | head -n1 | tr -s ' ' | cut -d' ' -f5`
    
    0 讨论(0)
  • 2020-12-12 16:11

    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
    
    0 讨论(0)
  • 2020-12-12 16:18

    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).

    0 讨论(0)
  • 2020-12-12 16:19
    ifconfig en1 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' 
    
    • Replace "en1" with the name of the nic card "eth0" or remove altogether "en1" - easy and useful solution.
    0 讨论(0)
  • 2020-12-12 16:19

    This works for me on Mac OS X:

    ifconfig en0 | grep -Eo ..\(\:..\){5}
    

    So does:

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

    Both are variations of examples above.

    0 讨论(0)
提交回复
热议问题