I am gonna have a validation of countries when users register. For example only Spain, The Netherlands and France in this login form and only USA in this login form.
I have a service running that gets me the country when i give it an ip address. The only bad thing is that the requests are expensive so I would like to optimize it.
I dont know much about ip addresses but i came up the following ‘algorithm’
A table with ip addresses up to 3 numbers. (for example: 11.111.11.x) And to save the country code in the same table. Or maybe up to 2 numbers if that is possible. Like this I will send less requests to the service.
Now comes the problem:
Is it always true that ip addresses starts with 3 numbers always come from the same country?
for example
80.224.6.x always for spain
80.224.7.x always for spain
or am I that lucky that i can say this:
80.224.x.x always for spain
etc…
In a word, no. Blocks of various sizes have been handed out to countries, to companies, to universities, etc, and there’s little rhyme or reason.
What you want is a geolocation library with a database. This one is free; there are better ones that cost money, but the free one is pretty good. Such a library provides an API you can use to semi-reliably look up the location given an IP address. At the country level, the reliability is pretty good.