How to get a visitor's IP in jQuery
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:
Is the visitor's IP address always accurate?
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.
How to detect if an IP address is that of a VPN service?
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:
This works but forces the jQuery script to make a second AJAX request, which is quite slow considering the long list of NordVPN servers. It would then be a good idea to build this list on the webserver and send it to the pages as a JavaScript table to save an AJAX connection. On the other hand, it would increase the size of the pages.
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 simplest solution to find the IP address of a visitor in jQuery
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: