How to get the Country according to a certain IP?
There are two approaches: using an Internet service and using some kind of local list (perhaps wrapped in a library). What you want will depend on what you are building.
For services:
- http://www.hostip.info/use.html (as mentioned by Mark)
- http://www.team-cymru.org/Services/ip-to-asn.html
For lists:
- http://www.maxmind.com/app/geoip_country (as mentioned by Orion)
You could roll your own by downloading the lists from the RIRs:
- ftp.arin.net/pub/stats/arin/delegated-arin-latest
- ftp.ripe.net/ripe/stats/delegated-ripencc-latest
- ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-latest
- ftp.apnic.net/pub/stats/apnic/delegated-apnic-latest
ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest
The format is documented in this README
Here's a nice free service with a public API: http://www.hostip.info/use.html
ipinfodb provides a free database and API for IP to country and vice versa. They use free data from MaxMind. The data gets updated every month, and it's a great free alternative with decent accuracy.
A lot of people (including my company) seem to use MaxMind GeoIP.
They have a free version GeoLite which is not as accurate as the paid version, but if you're just after something simple, it may be good enough.