View Single Post
Old 12. Dec 2009, 01:27 AM   #1 (permalink)
debtboy
Senior Member
 
debtboy's Avatar
 
Join Date: May 2009
Location: ~/
Posts: 128
Default IP Location script:

I made a simple little bash script (using a web API) which exposes the location (down to the nearest city) of any IP address.
You see similar things on websites written in javascript, but I figured someone might
benefit from seeing it as a shell script with a brief explanation.

Here is the script:
Code:
#!/bin/bash

echo ""
echo "Enter an IP Address or leave blank for your IP: "
read address

if [ "$address" == "" ]; then
     var_url="http://ipinfodb.com/ip_query.php"
else
     var_url="http://ipinfodb.com/ip_query.php?ip=$address"
fi

var_xml=`wget -q $var_url -O -`

var_ip=`echo $var_xml | grep -o "<Ip>[0-9 \.]*<\/Ip>" | \
     sed -e 's/<Ip>//' -e 's/<\/Ip>//'`

var_country=`echo $var_xml | grep -o "<CountryName>[A-Z a-z \s]*<\/CountryName>" | \
     sed -e 's/<CountryName>//' -e 's/<\/CountryName>//'`

var_state=`echo $var_xml | grep -o "<RegionName>[A-Z a-z \s]*<\/RegionName>" | \
     sed -e 's/<RegionName>//' -e 's/<\/RegionName>//'`

var_city=`echo $var_xml | grep -o "<City>[A-Z a-z \s]*<\/City>" | \
     sed -e 's/<City>//' -e 's/<\/City>//'`

echo ""
echo "IP Address:   $var_ip"
echo "Country:      $var_country"
echo "State/Region: $var_state"
echo "City:         $var_city"
echo ""
I'll give a brief explanination then a simple demonstration.
The first line #!/bin/bash is called she-bang it informs the kernel to use a bash shell to interpret this file.

echo sends things to the standard output, if not redirected (the screen in this case).
read accepts input from the command line when the <enter> key is pressed.

If was used to determine if an IP address was entered on the command line or if it was left blank.
If it was left blank, the API will use your IP address as input
(your ip address is always passed to a server during a request).

The var_url variable now holds the web API (automatic programming interface) address.

wget goes to the web address and returns the response which in our case was assigned to the var_xml variable.

In the next 4 lines, you can see where I pipe "|" the variable contents into grep searching for particular patterns
via regex (Regular Expressions) and then parse (strip off) the xml tags
via sed (stream editor) again using regex (Regular Expressions).
Regex is very powerful, but not so easy to explain.
Google will help if your interested.

The last section echoes some output to the screen. I send a text label or description and then the contents of each variable.

No lets see it in action...
__________________
[I][B]Linux, the choice of a GNU generation[/B][/I]
debtboy is offline   Reply With Quote