Finding client's public IP in Nodejs deployed on AWS EC2

Background to the issue:

My background is non-networked programming so I am new to web development. I’m in the process of teaching myself javascript. I am experimenting with node.js and have deployed it on a free AWS EC2 instance to play around with it. I wish to work with an IP geolocation API and therefore need to pull my laptop’s public IP address when I make a request to my server.

What I’ve tried:

I have seen a couple posts stating the correct way to do this in nodejs is:

    http.createServer(function (req, res) {
      req.socket.address
      ...

or in the case of proxies:

    http.createServer(function (req, res) {
      request.headers[x-forwarded-for]
      ...

Why my issue is different:

Neither of these methods have given me the desired value.

Object.entries(request.socket.address) yields an Amazon internal IP address which I would assume is some type of proxy since giving every instance its own globally unique IP would very quickly drain Amazon’s supply I image I’m sharing my instance IP with many other instances and this method is how the multiplex them, although I’m not certain. Just for the fun of it if someone knows more about about what this is I’d love to read into it.

Object.entries(request.headers) does not contain any 'x-forwarded-for' key/val

I will have to modify a portion of the values for security reasons but here are the values I received logged to the console:

    request.socket.address: address,::ffff:172.31.x.x,family,IPv6,port,80
    
    request.headers: host,ec2-54-205-x-x.compute-1.amazonaws.com,connection,keep-alive,pragma,no-cache,cache-control,no-cache,user-agent,Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.68,accept,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8,referer,http://ec2-54-205-x-x.compute-1.amazonaws.com/,accept-encoding,gzip, deflate,accept-language,en-US,en;q=0.9

I’ve read through the nodejs docs a bit and can’t figure out what else I could do. Your help is greatly appreciated in moving me forward. Thanks ahead of time 🙂

26 thoughts on “Finding client's public IP in Nodejs deployed on AWS EC2”

Leave a Comment