Retrieving the client request ip address

18,941

Solution 1

You can get this information by fetching it from an open IP

https://api.ipdata.co/

fetch("https://api.ipdata.co")
  .then(response => {
    return response.json();
   }, "jsonp")
  .then(res => {
    console.log(res.ip)
  })
  .catch(err => console.log(err))

Solution 2

It seems like https://api.ipdata.co doesn't work anymore, even when specifying a key. I ended up using (typescript):

private getMyIp() {
  fetch('https://api.ipify.org?format=json').then(response => {
    return response.json();
  }).then((res: any) => {
    this.myIp = _.get(res, 'ip');
  }).catch((err: any) => console.error('Problem fetching my IP', err))
}

This is a good reference for other services: https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only

Solution 3

This works!

async componentDidMount() {
      
    const response = await fetch('https://geolocation-db.com/json/');
    const data = await response.json();
    this.setState({ ip: data.IPv4 })
    alert(this.state.ip)

}

use it in jsx as

{this.state.ip}

Share:
18,941
Josiah Colvin
Author by

Josiah Colvin

Updated on June 22, 2022

Comments

  • Josiah Colvin
    Josiah Colvin almost 2 years

    This post isn't really a question anymore; I just want to post this to help other people out in the future to avoid lost time.

    Goal: Retrieve the client IP address and set some specific values based on certain octet in IP.

    I was developing a react web-app for my company and needed to support three facilities. The three locations of-course existed in different geographical regions and had slightly different IP schema's.

    I needed to set some session identifier based on an octet value from the client IP. To do so, I did the following steps.

    1. Setup express route for user to hit on initial visit of app.
    2. Get client IP and store in const/var.
    3. Explode IP string by ".".
    4. Perform If/Then or Switch to determine value of desired octet.
    5. Set some session/logic within matching condition.

    Thanks to express, the req object contains an ip key with the value of the requests IP address. We can utilize this or some other third party library to get the needed info. Of course there are better/more secure ways to do this, but this is a simple method I've researched and setup. Definitely thanks to community for helping me resolve my issue with this.

        apiRouter.route('/test')
    
        .get((req, res) => {
            const request_ip = req.ip;      // Returns string like ::ffff:192.168.0.1
            const ip_array = request_ip.split('.')      // Returns array of the string above separated by ".". ["::ffff:192","168","0","1"]
    
            // The switch statement checks the value of the array above for the index of 2. This would be "0"
            switch(ip_array[2]) {
                case('0'):
                    res.json({'request-ip':ip_array, 'location':'Location A'});
                    break;
                case('1'):
                    res.json({'request-ip':ip_array, 'location':'Location B'});
                    break;
                case('2'):
                    res.json({'request-ip':ip_array, 'location':'Location C'});
                    break;
                default:
                    res.json({'request-ip':ip_array, 'location':'Default Location'});
            }
    
        })
    

    One of my main issues was that I was developing on my local laptop. My node server was running express here. I was also trying to get my request ip from my local machine. This didn't make sense because I was constantly getting back "::1" as my request IP. Baffled, I did much research and finally found it to be an obvious PEBKAC issue. Thanks to nikoss in this post, it made all the sense in the world.

  • Josiah Colvin
    Josiah Colvin about 6 years
    Thanks Joe. This too is useful and a great option!
  • Rik van Velzen
    Rik van Velzen over 3 years
    This url provides geo location data that is not accurate
  • JimmyTheCode
    JimmyTheCode over 2 years
    FYI, ipdata.co and ipify.org are both blocked by commonly used ad-blockers/chrome extensions.
  • JimmyTheCode
    JimmyTheCode over 2 years
    FYI, ipdata.co and ipify.org are both blocked by commonly used ad-blockers/chrome extensions.
  • JimmyTheCode
    JimmyTheCode over 2 years
    FYI, ipdata.co and ipify.org are both blocked by commonly used ad-blockers/chrome extensions.