skip to Main Content
const peerConnection = new RTCPeerConnection({ iceServers: [] });
     peerConnection.createDataChannel('');

     peerConnection.createOffer()
    .then((offer) => peerConnection.setLocalDescription(offer))
    .catch((error) => console.log(error));

    peerConnection.onicecandidate = (event) => {
    if (event.candidate) {
      console.log(`Client's IP address is ${event.candidate.address}`);
     }
   };

3

Answers


  1. Extract IP address from the candidate attribute

    const ipAddress = event.candidate.candidate.split(' ')[4];
    

    Print IP address

    console.log('IP address:', ipAddress);
    
    Login or Signup to reply.
  2. In JavaScript, you can retrieve the IP address of a user’s device through various methods.
    The most common way to do this is by using a service that provides your application with the
    user’s IP address. Here’s an example using a popular service called “ipify”:

    fetch('https://api.ipify.org?format=json')
                                .then(response => response.json())
                                .then(data => {
                                  const ipAddress = data.ip;
                                  console.log('Your IP address is: ' + ipAddress);
                                })
                                .catch(error => {
                                  console.error('Error fetching IP address:', error);
                                });

    In this code:

    1. We use the fetch function to make a GET request to the “https://api.ipify.org?format=json” URL.
      This service responds
      with JSON data containing the user’s IP address.

    2. We parse the JSON response using the .json() method, which returns a
      JavaScript object.

    3. We extract the IP address from the object and log it to the console.

    Please note that this method relies on an external service, so it requires an internet
    connection and is subject to rate limits imposed by the service provider. Additionally, the
    user’s IP address may not be 100% accurate due to factors like VPNs or proxy servers.

    If you want to get the client’s IP address from a server-side perspective (e.g., in a Node.js
    environment), the method may differ based on your server framework or technology stack.
    Typically, you can access the client’s IP address from the request object. For example, in
    Node.js with Express:

    const express = require('express');
                                const app = express();
                                
                                app.get('/getip', (req, res) => {
                                  const clientIpAddress = req.ip; // This gives you the client's IP address
                                  res.send(`Your IP address is: ${clientIpAddress}`);
                                });
                                
                                app.listen(3000, () => {
                                  console.log('Server is running on port 3000');
                                });
    

    In this server-side example, req.ip gives you the client’s IP address as
    provided by Express. Please note that the accuracy of this method can also be affected by
    proxies and load balancers in some cases.

    Login or Signup to reply.
  3. Due to security and privacy concerns, you can’t directly get a user’s public IP address when JavaScript is running in a web browser. But you can use API calls to third-party sites to get the user’s public IP address.

    Here’s how you can use JavaScript and an outside service to find the IP address:

    1. Using a free service for IP API

    To get the public IP address, you can use a tool like ipify.

    fetch('https://api.ipify.org?format=json')
        .then(response => response.json())
        .then(data => {
            console.log(data.ip);
        })
        .catch(error => {
            console.log('Error:', error);
        });

    2. Using WebRTC (Public IP Unreliable)

    WebRTC can be used to find out the user’s private and maybe even public IP address. But this method doesn’t guarantee a public IP, and it may reveal private IPs, which can be a privacy issue.

    function findIP(onNewIP) {
        var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
        var pc = new myPeerConnection({
            iceServers: []
        }),
        noop = function() {},
        localIPs = {},
        ipRegex = /([0-9]{1,3}(.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
        key;
    
        function iterateIP(ip) {
            if (!localIPs[ip]) onNewIP(ip);
            localIPs[ip] = true;
        }
    
        pc.createDataChannel("");
    
        pc.createOffer(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);
        }, noop);
    
        pc.onicecandidate = function(ice) {
            if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
            ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
        };
    }
    
    findIP(ip => console.log('your IP is ' + ip));

    Remember that if you use an external service like in the first way, you’ll be dependent on that service’s availability and may run into rate limits if you make too many requests in a short amount of time.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search