Fork me on GitHub

WAN IP from a bash script

Today I was, once again, faced with a problem where a bash shell script was the best solution. Seeing that I spend most of my time writing php code, the shell script was a welcome break.

A few minutes into my coding of the shell script, I realized that I needed the WAN IP address of the server I was working on. My first thought was to write some sort of fancy shell interface into the router where I could query the information I needed and use it in my shell script, but that would have been a bit of overkill. So what I did was put a nice little php script at that simply prints the remote IP address that is accessing the script.  Now I can easily get the IP using the following line in my script:

IP=`wget -q -O -`

I thought this bit of information my be helpful to someone, so I decided to put a quick note about it here. I've included examples and a bit more explanation after the break. 

Enjoy ...

An example script:


WANIP=`wget -q -O -`
echo "Your IP adress is $WANIP"
echo "Thank you and have a great day!"

The php script at

<?php echo $_SERVER['REMOTE_ADDR']; ?>

What's wget?

wget is a linux command line utility to 'get' something from a website. From the wget man page, it is "The non-interactive network downloader."

Let's say there's a file you want to download to your home directory on a linux server. You've got an open ssh session to the server and you have fileZilla on your PC to transfer files to the server. You could always download the file to your PC and then transfer it to the server. What if the file is 200MB? That doesn't sound like a very good solution then, does it? What you could do, is type:


from the linux command line, and it would save the file right there on the server. 

So, from our example, if you were to type:


wget would save a file named index.html to whatever directory you're in. The contents of the file would be your IP address and wget would show a bunch of information you don't need on the screen. That's where the -q option comes in. Typing:

wget -q

would download the file without the output from wget. However, in our shell script, we just want the contents of that file. The -O option tells wget that we are going to save the output to a file and it expects a filename to follow. The - as the filename tells it to print the output to the stdout. In essence, we are saving the output to a file that is the stdout. So, typing:

wget -q -O - 

will print just your WAN IP address at the command line. 

Hope this has been informative and helpful.