How to get the client IP address in Javascript

By FoxLearn 2/14/2025 8:47:39 AM   71
In JavaScript, retrieving a user's IP address directly is not possible due to security restrictions.

However, there are two main methods you can use to obtain the IP address: one for the private IP using WebRTC and another for the public IP via third-party services.

To get a user’s public IP, you’ll need to send a request to a server that can return the IP. For this, you can easily deploy a simple JavaScript script using Node.js and Express, and request it from your server to get the client’s IP.

1. Using WebRTC to Retrieve the Private IP Address

WebRTC's RTCPeerConnection interface allows for peer-to-peer connections, and we can exploit this to retrieve a user's private IP address.

Here’s how it works:

  • The createOffer() method generates a session description that includes media stream information, and through this process, you can extract the user's private IP address.
  • This process returns a Promise, which, once fulfilled, provides the necessary IP information.
/**
 * Get the user IP using WebRTC
 * @param onNewIP {Function} - listener function to expose the IP locally
 */
function getUserIP(onNewIP) {
    // Compatibility for different browsers
    var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
    var pc = new myPeerConnection({ iceServers: [] });
    var noop = function() {};
    var localIPs = {};
    var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;

    // Iterate over IP addresses
    function iterateIP(ip) {
        if (!localIPs[ip]) {
            onNewIP(ip);
            localIPs[ip] = true;
        }
    }

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

    // Create an offer and set local description
    pc.createOffer().then(function(sdp) {
        sdp.sdp.split('\n').forEach(function(line) {
            if (line.indexOf('candidate') < 0) return;
            line.match(ipRegex).forEach(iterateIP);
        });
        pc.setLocalDescription(sdp, noop, noop);
    }).catch(function() {
        // Handle connection failure
    });

    // Listen for ICE candidate events
    pc.onicecandidate = function(ice) {
        if (ice && ice.candidate && ice.candidate.candidate && ice.candidate.candidate.match(ipRegex)) {
            ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
        }
    };
}

// Usage Example:
getUserIP(function(ip){
    alert("Private IP: " + ip);
});

2. Using a Third-Party Service to Get the Public IP

For the public IP address, you’ll need to rely on third-party services, since JavaScript running in the browser does not have direct access to the user's public IP.

For example, Using ipify (Recommended for HTTPS)

// Using ipify service for secure HTTPS requests
fetch('https://api.ipify.org?format=json')
  .then(response => response.json())
  .then(data => {
      console.log("Public IP Address: ", data.ip);
  })
  .catch(error => console.log("Error: ", error));

You can use it with JSONP:

<script type="application/javascript">
  function getIP(json) {
    document.write("My public IP address is: ", json.ip);
  }
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

Alternatively, you can fetch an object using a JSON request with jQuery:

$.getJSON('https://api.ipify.org?format=json', function(data){
    console.log(data.ip);
});

For example, Using ipinfo.io (HTTP and HTTPS)

// Using ipinfo.io service
fetch('https://ipinfo.io/json')
  .then(response => response.json())
  .then(data => {
      console.log("Public IP Address: ", data.ip);
  })
  .catch(error => console.log("Error: ", error));

Both services provide the user's public IP, and you can choose based on whether you need secure HTTPS connections or not.