Find Country for IP


In this blog we will look at how we can find the originating country for a given IP address. I do this to quickly check this information for all IP addresses logged in my Apache logs. I will only use the command line but you can put all this in a script and do a lot of different stuff with it. Again there might be simpler ways to achieve this so feel free to research.
NOTE* We will be using curl for this example so if you don’t already have it installed just type
1 |
yum -y install curl |
So assuming our logs files are under /var/log/httpd/ let’s first see a quick command to find all the unique IP addresses in my access log file. Remember your log file names may be different.
The command below will show you all the IP addresses from the file access_log. I have printed this file and then cut the first field. The -d option provides the delimiter.
1 |
cat /var/log/httpd/access_log | cut -d" " -f1 |
You may see a lot of the addresses repeating so let’s only display the unique entries.
1 |
cat /var/log/httpd/access_log | cut -d" " -f1 | sort -u |
Alright this looks better as we only see unique IP’s now. You can easily count the number of unique IP addresses like below but we are not interested in counting for now.
1 |
cat /var/log/httpd/access_log | cut -d" " -f1 | sort -u | wc -l |
Now let’s just save the output of our first command in a text file so we have all the unique IP’s saved.
1 |
cat /var/log/httpd/access_log | cut -d" " -f1 | sort -u >> iplist |
If want to run this on multiple access log files then just add a * at the end of the file name.
1 |
cat /var/log/httpd/access_log* | cut -d" " -f1 | sort -u >> iplist |
Time to find out where each of these IP’s come from. I found a neat little way to check this information. Let’s first try with a single IP address.
1 |
curl ipinfo.io/8.8.8.8 |
This will give you the following output.
1 2 3 4 5 6 7 8 9 10 |
{ "ip": "8.8.8.8", "hostname": "google-public-dns-a.google.com", "city": "Mountain View", "region": "California", "country": "US", "loc": "37.3860,-122.0838", "org": "AS15169 Google Inc.", "postal": "94035" } |
We can find a lot of information but for the sake of this post I am only interested in the country. We can repeat this command for all the IP’s from the file we saved earlier like this:
1 |
for l in `cat iplist`; do echo "`curl ipinfo.io/$l`";done; |
And your console will start displaying this information for each IP one by one but this is not useful yet as I only want to display the country in a neat way.
1 |
for l in `cat iplist`; do echo "`curl -s ipinfo.io/$l | head -6 | tail -1`";done; |
And the output should be something like
1 2 3 4 5 6 7 8 9 10 |
"country": "JP", "country": "UA", "country": "PK", "country": "ID", "country": "ID", "country": "ID", "country": "ID", "country": "CN", "country": "CN", "country": "CN", |
Ok so not so neat and clean but you get the idea. I will continue to improve this example but you should try your own. Have fun.