Recently I was working on a project where we were isolating IP addresses by country. In the process, I found an easy little tool built right into OS X called ip2cc. Using ip2cc, you can lookup what country an IP is in. To do so, simply run ip2cc followed by a name or ip address. For example, to lookup apple.com you might run:
ip2cc apple.com
Or to lookup Much Music, you might run:
ip2cc muchmusic.ca
The output would be:
IP::Country modules (v2.28)
Copyright (c) 2002-13 Nigel Wetters Gourlay
Database updated Wed May 15 15:29:48 2013
Name: muchmusic.com
Address: 199.85.71.88
Country: CA (Canada)
You can just get the country line:
ip2cc apple.com | grep Country:
To just get the country code:
ip2cc apple.com | grep Country: | awk '{ print $2 }'
Finally, ip2cc is located at /usr/bin/ip2cc so we’ll complicate things just a tad by replacing the hostname with the current IP (note that private IPs can’t be looked up, so this would only work if you’re rocking on a wan ip or feeding it what a curl from a service like whatismyip brings back):
ip2cc `ipconfig getifaddr en0` | grep Country: | awk '{ print $2 }'