Get visitor IP address using Javascript

September 24, 2020
-
Emma Jagger

Engineer, maker, Google alumna, CMU grad

How to get client IP addresses using Javascript


Trying to build some customisation into your website? Or simply block some malicious IPs from accessing your content?

This guide covers the easiest way to retrieve a visitor IP address using javascript.



We will cover 2 methods:

  • The first will be using the open-source WebRTC method from diafygi
  • The second will use our simple and free IP geolocation API

Method 1: Use new WebRTC method

This method uses diafygi "STUN IP Address requests for WebRTC".

This code snippet is based on newly-released WebRTC support in Chrome and Firefox that allows request for STUN servers to be made, resulting in the ability to access local and public IP addresses for your visitors.

With a small Javascript code you could easily perform these requests and make the IP data available in other parts of your page to be analysed and use for customisation or blocking.

The good news is that these calls can't be blocked by ad blocking plugins and widgets because they are made outside of the XMLHttpRequest instance. Given that 20 to 30% of the internet users are browsing with Adblockers, this is perfect if you want to ensure aconsistent experience for all your users.

Copy and paste the following code into your web page:

  
  //get the IP addresses associated with an account
	function getIPs(callback){
    var ip_dups = {};

    //compatibility for firefox and chrome
    var RTCPeerConnection = window.RTCPeerConnection
        || window.mozRTCPeerConnection
        || window.webkitRTCPeerConnection;
    var useWebKit = !!window.webkitRTCPeerConnection;

    //bypass naive webrtc blocking using an iframe
    if(!RTCPeerConnection){

        var win = iframe.contentWindow;
        RTCPeerConnection = win.RTCPeerConnection
            || win.mozRTCPeerConnection
            || win.webkitRTCPeerConnection;
        useWebKit = !!win.webkitRTCPeerConnection;
    }

    //minimal requirements for data connection
    var mediaConstraints = {
        optional: [{RtpDataChannels: true}]
    };

    var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

    //construct a new RTCPeerConnection
    var pc = new RTCPeerConnection(servers, mediaConstraints);

    function handleCandidate(candidate){
        //match just the IP address
        var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
        var ip_addr = ip_regex.exec(candidate)[1];

        //remove duplicates
        if(ip_dups[ip_addr] === undefined)
            callback(ip_addr);

        ip_dups[ip_addr] = true;
    }

    //listen for candidate events
    pc.onicecandidate = function(ice){

        //skip non-candidate events
        if(ice.candidate)
            handleCandidate(ice.candidate.candidate);
    };

    //create a bogus data channel
    pc.createDataChannel("");

    //create an offer sdp
    pc.createOffer(function(result){

        //trigger the stun server request
        pc.setLocalDescription(result, function(){}, function(){});

    }, function(){});

    //wait for a while to let everything done
    setTimeout(function(){
        //read candidate info from local description
        var lines = pc.localDescription.sdp.split('\n');

        lines.forEach(function(line){
            if(line.indexOf('a=candidate:') === 0)
                handleCandidate(line);
        });
    }, 1000);
  }

//Test: Print the IP addresses into the console
getIPs(function(ip){console.log(ip);});

  

Now you can use the following function to get the IP as soon as it's found:

  
	//Test: Print the IP addresses into the console
	getIPs(function(ip){console.log(ip);});
  

Method 2: Use Abstract's IP geolocation API

Abstract provides a free IP Geolocation API that has a method to retrieve the IP of a visitor.

You can use learn more and get your free API key here: https://www.abstractapi.com/ip-geolocation-api