Network connections by geographic location

A couple of days ago, a colleague made me aware that iplocationtools.com exposes a cool web service that allows you to get the geographical location based on an IP address.

Here's a script that parses the IP addresses the workstation is connected to, and then resolves each one to its geographical location:




clear; netstat -an | grep ESTABLISHED | awk {'print $5'} | sort -u | sed "s/\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\).*/\1/g" | while read sw; do url="http://iplocationtools.com/ip_query.php?ip=$sw"; curl $url -s | ~/tools/xmlstarlet sel -t -m "/Response/CountryName" -v . -o "," -m "/Response/City" -v . -; done


Note the dependancy on xmlstarlet that allows easy extraction of values from XML content. Unlike xsltproc which demands a XSL file, xmlstarlet allows you to run an Xpath query, building the needed XSL file by itself.

And here's a rundown of the script:

clear just clears the shell screen.

clear; netstat -an -> get a list of connections, without attempting to solve names

clear; netstat -an | grep ESTABLISHED -> keep only lines containing ESTABLISHED, that is active connections


clear; netstat -an | grep ESTABLISHED | awk {'print $5'} -> keep only the 5th field from each line, containing the IP address we are connected to

clear; netstat -an | grep ESTABLISHED | awk {'print $5'} | sed "s/\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\).*/\1/g" -> strip out the port number from the IP address.

Without sed, netstat outputs stuff like 74.125.43.83.443 where 443 is the TCP port we are connected to.
To strip out the port, we can use sed, matching IP addresses to 4 groups of digits separated by a dot, i.e. \([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\). This is later matched by the "\1" reference.

clear; netstat -an | grep ESTABLISHED | awk {'print $5'} | sort -u | sed "s/\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\).*/\1/g" | while read sw; do command done

What follows is a while loop, where we read each ip address, one at a time and execute the localization command.

command is:

url="http://iplocationtools.com/ip_query.php?ip=$sw"; curl $url -s | ~/tools/xmlstarlet sel -t -m "/Response/CountryName" -v . -o "," -m "/Response/City" -v . -

We use curl to get an XML document that lists the geolocation of the IP we and then process the XML document using xmlstarlet, by extracting the country and city name.