Loading
Home ›
Tech Tip: Getting Your MAC and IP Address In a Script
Dec 31, 2009 By Sandeep Swaminathan
in
Ever wanted to get the MAC or IP address of your computer in a Linux shell script? The following two commands should work on most flavours of Linux/Unix.
To get your IP address:
/sbin/ifconfig \ | grep '\<inet\>' \ | sed -n '1p' \ | tr -s ' ' \ | cut -d ' ' -f3 \ | cut -d ':' -f2
To get your MAC address (Hardware address):
/sbin/ifconfig \ | grep 'eth0' \ | tr -s ' ' \ | cut -d ' ' -f5
Note that this retrieves the address of the eth0 interface by default.
______________________
Trending Topics
| Dia - The Diagram Creation Tool | Feb 13, 2012 |
| You Need A Budget | Feb 10, 2012 |
| The Linux powered LAN Gaming House | Feb 08, 2012 |
| Creating a vDSO: the Colonel's Other Chicken | Feb 06, 2012 |
| Your CMS Is Not Your Web Site | Feb 01, 2012 |
| Casper, the Friendly (and Persistent) Ghost | Jan 31, 2012 |
- Dia
2 hours 24 min ago - Service units, is a daemon
4 hours 16 sec ago - Tcp
4 hours 20 min ago - Lamenting more development of Dia
10 hours 12 min ago - multiboot that works well for me
20 hours 2 min ago - What's a good, AFFORDABLE aka
20 hours 3 min ago - Employment Posters
1 day 11 hours ago - Sure the best distro is
1 day 12 hours ago - BeOS was the best
1 day 15 hours ago - I use Wireshark on a daily
1 day 20 hours ago





Comments
How about this: hostname -i
How about this:
hostname -i
this one-liner shows all IP addresses for all interfaces
/sbin/ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | sort | awk '{print "# "$1}'
www.freephile.com
www.rundlett.com
bash script for all unixes at
http://bash.cyberciti.biz/misc-shell/read-local-ip-address/
www.freephile.com
www.rundlett.com
get your IP
ifconfig eth0
| sed -n '/inet addr:/p'
| cut -d: -f2
| cut -d" " -f1
all in one
ifconfig ath0 | perl -ne 'm/.*HWaddr (\S+).*/ && print "$1 ";m/.*inet addr:(\S+)/ && print "$1\n"'
Perl could be used for extracting both IPv4 and IPv6:
# ifconfig | perl -ne '(s|^\s+inet6\s+addr:\s*([0-9a-f:/]+)\s+.*|${1}| or s|^\s+inet\s+addr:\s*([0-9.]+)\s+.*|${1}|) and print;' ****************************** ****************************** 127.0.0.1 ::1/128showing mac address
To show MAC:
cat /sys/class/net/eth0/address
egrep
How about...
IP:
ifconfig eth1 | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' | sed -n '1p'
MAC:
ifconfig eth1 | egrep -o '([[:xdigit:]]{2}[:]){5}[[:xdigit:]]{2}'
This provides validation and also the regexp can be used elsewhere to find IPs and MACs
IP: ip addr show dev eth0 |
IP:
ip addr show dev eth0 | sed -e's/^.*inet \([^ ]*\)\/.*$/\1/;t;d'
MAC:
ip addr show dev eth0 | sed -e's/^.*link[^ ]* \([^ ]*\) .*$/\1/;t;d'
or with /sbin/ifconfig
IP:
/sbin/ifconfig wlan0 | sed -e's/^.*inet addr:\([^ ]*\) .*$/\1/;t;d'
MAC:
/sbin/ifconfig eth0 | sed -e's/^.*HWaddr \([^ ]*\) .*$/\1/;t;d'