Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to get your IP address in shell scripts

Context: On *nix systems, one may get the IP address of the machine in a shell script this way:

ifconfig | grep 'inet' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}'

Or this way too:

ifconfig | grep 'inet' | grep -v '127.0.0.1' | awk '{print $2}' | sed 's/addr://'

Question: Would there be a more straightforward, still portable, way to get the IP address for use in a shell script?

(my apologies to *BSD and Solaris users as the above command may not work; I could not test)

like image 399
Eric Platon Avatar asked Mar 02 '10 08:03

Eric Platon


4 Answers

you can do it with just one awk command. No need to use too many pipes.

$ ifconfig | awk -F':' '/inet addr/&&!/127.0.0.1/{split($2,_," ");print _[1]}'
like image 82
ghostdog74 Avatar answered Nov 03 '22 15:11

ghostdog74


you give direct interface thereby reducing one grep.

ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'
like image 38
coder Avatar answered Nov 03 '22 16:11

coder


Based on this you can use the following command

ip route get 8.8.8.8 | awk 'NR==1 {print $NF}'
like image 3
Ahmad Yoosofan Avatar answered Nov 03 '22 15:11

Ahmad Yoosofan


Look here at the Beej's guide to networking to obtain the list of sockets using a simple C program to print out the IP addresses using getaddrinfo(...) call. This simple C Program can be used in part of the shell script to just print out the IP addresses available to stdout which would be easier to do then rely on the ifconfig if you want to remain portable as the output of ifconfig can vary.

Hope this helps, Best regards, Tom.

like image 1
t0mm13b Avatar answered Nov 03 '22 16:11

t0mm13b