Get the IP address of a machine. Just the IP, no junk.

/sbin/ifconfig -a | awk '/(cast)/ { print $2 }' | cut -d':' -f2 | head -1

By: d4n3sh
2009-04-15 06:44:18

5 Alternatives + Submit Alt

What Others Think

Nice, I use this: /sbin/ifconfig -a |sed -n 's/.*addr:\(.*\)[ ]*Bcast.*/\1/p'
elzapp · 683 weeks and 5 days ago
awful !
megerdin · 683 weeks and 5 days ago
My Linksys router running Freewrt doesn't have ifconfig, and ip addr show includes CIDR notation for some annoying reason. So, I use this to get my external IP (not mine, something I found googling): ip -o addr show eth0 | awk '$3 == "inet" {split($4,i,"/"); print i[1]; exit}'
sud0er · 683 weeks and 5 days ago
Thanks elzapp, way better :D
d4n3sh · 683 weeks and 4 days ago
Sorry, I feel bad for voting you down after all the effort you put into this one, but you just need to use "hostname -i"
kFiddle · 683 weeks and 3 days ago
voted down because: a) It's already in the archive b) It does not handle the situation when there are multiple network interfaces active. Assuming that the default route is via the network interface of interest: /sbin/ifconfig $(netstat -rn | grep "^" | awk '{print $8}') | awk -F: '/inet addr/ {printf("%s\n",substr($2,1,index($2," "))) }'
mpb · 683 weeks and 1 day ago
/sbin/ifconfig -a |sed -n 's/.*addr:\(.*\)[ ]*Bcast.*/\1/p' This doesn`t work for me. - debian lenny - GNU sed Version 4.1.5
P17 · 680 weeks and 5 days ago
@kFiddle - nice one, but hostname -i returns for me - better is recommended hostname -I with uppercase I - gives me IPv6 too
sashametro · 474 weeks ago
seofox · 26 weeks and 2 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: