user1031782
user1031782

Reputation: 186

Remote IP from request on http server

is there any way to know the remote IP adress form a request on on the http server? Using "net" for a socket connection is socket.remoteAddress but for the http server I get undifined for the same .remoteAddress

Regards

Upvotes: 15

Views: 19010

Answers (3)

T.Todua
T.Todua

Reputation: 56341

here is sample of getting IP address on node server:

const http = require('http');
const server = http.createServer();
server.listen(5432, () => { });
server.on('connection', (stream) => {
  console.log("someone connected: " + stream.remoteAddress);
});

Upvotes: 0

sarnold
sarnold

Reputation: 104020

You can use the request.connection method to retrieve the net.Socket object, where you can then use your socket.remoteAddress property.

Upvotes: 15

JustTrying
JustTrying

Reputation: 764

I'm just adding this because I came across this article and it still took me a little bit of time to figure out it was as you see in the following:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello ' + req.connection.remoteAddress + '!');
    console.log("request received from: " + req.connection.remoteAddress);
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

Upvotes: 22

Related Questions