Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Wednesday, December 16, 2015

Efficient way to get your IP address in shell scripts

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)

Answer by coder for Efficient way to get your IP address in shell scripts


you give direct interface thereby reducing one grep.

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

Answer by t0mm13b for Efficient way to get your IP address in shell scripts


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.

Answer by ghostdog74 for Efficient way to get your IP address in shell scripts


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]}'  

Answer by David J Merritt for Efficient way to get your IP address in shell scripts


ifconfig | grep 'broadcast\|Bcast' | awk -F ' ' {'print $2'} | head -n 1 | sed -e 's/addr://g'

Answer by Gautham Shervegar for Efficient way to get your IP address in shell scripts


May be this could help.

 more /etc/hosts | grep `hostname` | awk '{print $1}'  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 71

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.