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