There are many applications for which a developer needs to collect information about a web page's visitor. Whether it is to personalize content, identify individuals, secure access to resources, or collect statistics, it becomes necessary to determine visitors' IP addresses.
Since there is no direct method to obtain the visitor's IP address, it will be necessary to query a server that will return the client's address. There are many free services available, such as https://api.myip.com, which returns the IP address in JSON format.
On the jQuery side, it is, therefore, necessary to establish an AJAX connection to the myip.com server, which can be written as follows:
By looking more precisely at the server's answer, it is possible to see that it contains some information about the country corresponding to the client's IP address:
It happens very often that several users share an IP address. This is the case for people who connect to the Internet via a VPN service to protect their identity or circumvent restrictions based on IP address. On the server-side, all these people will be seen with the same IP address. This is also the case for a jQuery script.
For a web page, this can have unexpected consequences. For example, if a jQuery script relies solely on the IP address to collect statistics, the inaccuracy will reflect the statistics.
It becomes necessary to have a way to detect if the visitor's IP address corresponds to that of a VPN.
IP addresses of VPN services can be discovered by different means. To take a well-known example, NordVPN exposes its list or servers at https://api.nordvpn.com/server. For information, it is this address that their clients use to update their internet server list.
A jQuery script would have to retrieve the JSON data from the server list, then collect all IP addresses, and finally check if the visitor's address is part of this list. Here is how to get a list of all NordVPN servers addresses:
Once this is done for NordVPN, it must also be implemented for all other existing VPN services to ensure that your script correctly detects visitors behind a VPN.
The solutions listed above work but require a lot of effort to implement and maintain.
The easiest solution is to use a free service that allows both to get the visitor's IP address in jQuery and detect if this visitor is using a VPN. This service is called Abstract IP Geolocation. Here is how to use it: