11

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
  • 145
  • 1
  • 2
  • 9
  • Is your main goal to find the location of the user rather than getting their ip? – Joe Warner Mar 13 '18 at 13:48
  • No, finding the request IP is more important in this scenario. I could use some GeoLocator library I assume is what you mean. I guess I could use the google api for location, but I just need a simple solution for setting some site specific details. Thanks Joe. – Josiah Colvin Mar 13 '18 at 13:51
  • That's fine I was going to suggest just using navigator.geolocation.getCurrentPosition but if you need IP that's understandable – Joe Warner Mar 13 '18 at 13:53
  • Thanks for the quick suggestion Joe. That, albeit useful, wouldn't be ideal in this scenario IMO. A great alternative option though! – Josiah Colvin Mar 13 '18 at 13:57
  • I've answered with i think would be the easiest/best solution if you need a codepen let me know – Joe Warner Mar 13 '18 at 13:59
  • Nah, I get where you're going with that response. I could use that fetch within react to identify the user location/ip schema. Great option. I didn't know about that api. I'll keep this one in mind for future use-case. Appreciate it Joe. – Josiah Colvin Mar 13 '18 at 14:06
  • no worries :) have a nice day – Joe Warner Mar 13 '18 at 14:12

5 Answers5

6

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))
Joe Warner
  • 3,335
  • 1
  • 14
  • 41
6

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}

Vikas Borse
  • 61
  • 1
  • 1
5

It seems like https://api.ipdata.co doesn't work anymore, even when specifying a key. I ended up using Ipify (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 alternative IP retrieval services: https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only

ian
  • 695
  • 2
  • 9
  • 19
-1

If https://api.ipdata.co doesn't work you can use geolocation-db.com/json. Advantage of geolocation it also gives you other important values like latitude, longitude, country, state, zip

fetch(`https://geolocation-db.com/json/`)
    .then(res => res.json())

You can console.log(...) the res.json() to view the JSON values.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Ashish
  • 63
  • 5
-3

You can use this one as well.

fetch('https://get-ip-only.herokuapp.com/') .then(r => r.json()) .then(resp => console.log(resp.ip))

https://get-ip-only.herokuapp.com/ This API provides you the IP only.

mymiracl
  • 583
  • 1
  • 16
  • 24