3

I've been trying for a while to get the ip address of the client (me) using Koajs; however, I keep getting the local host address of ::1

I tried using this.request.ip and this.request.headers['x-forwarded-for'] with app.proxy set to true, still I get the arbitrary local host ip.

I do need the IP address for the geolocation app that I'm building.

Here's my code:

var koa = require('koa');
var app = koa();

app.proxy = true;


app.use(function *(){
    this.body = this.request.ip; // also tried request.headers['x-forwarded-for'];
});

 app.listen(3000);
  • Are you accessing this from the same computer that the site is hosted on? if so it makes sense that you are getting the local host address. – eandersson Jul 10 '16 at 07:44
  • And where are the requests coming from? Do you run both the server and the client on the same machine? – Some programmer dude Jul 10 '16 at 07:44
  • @eandersson Yes I am. The line 'app.listen(3000)' allows me to run the app on http://localhost:3000/ I just want it to print my ip address in the form xx.xxx.xxx.xx, whereas this.body = this.request.ip; prints ::1 which is the arbitrary localhost address – user3037589 Jul 10 '16 at 08:16
  • So you want the IPv4 localhost address, i.e. `127.0.0.1` and not the IPv6 localhost address `::1`? Then in the client try connect explicitly to `127.0.0.1:3000`, otherwise the client will pick the first in the list of aliases for `localhost` (which in your case apparently is the IPv6 address). – Some programmer dude Jul 10 '16 at 09:44

1 Answers1

-1

try to change to

this.body = this.req.headers['x-real-ip'];
Alongkorn
  • 3,968
  • 1
  • 24
  • 41