How to get an IP address in Javascript

Last Updated Nov 19, 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

Important: This method is now no longer supported by several browsers.

Continue the reading below to see another free alternative.

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);});
  

There are several downsides to using this method. Not only is it not supported by a few browsers, but it also lacks certain information that you can otherwise tell from an IP address, such as whether the IP address is using a proxy or VPN.

Method 2: Use Abstract's IP detection API

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


This simple to use, yet powerful API provides the following features:

  • Retrieve the IP of a visitor
  • Retrieve the location of a visitor
  • Retrieve the location of an IP

The API is free to use and allow thousands of calls per month. Using it is pretty simple and only require an API key you can get for free by signing up here. The documentation can be found on the documentation page: ip geolocation documentation. In addition, you can see our review of the best IP geolocation API as well as try our "What is my IP address and location?" tool for non-technical users.

Abstract's IP Geolocation API comes with Javascript libraries, code snippets, guides, and more.
Get started