blunrib blunrib - 5 months ago 32
Javascript Question

Node HTTP resolution

So you can make a node HTTP GET request like so:

var http = require('http');
var options = {
host: 'stackoverflow.com',
};

var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
});

req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});


I want to see what IP address that
http.get
is going to? How does the node HTTP lib determine which IP address to use if a given DNS resolves to multiple IPs?

By multiple IPs i mean something like:

dig +short stackoverflow.com
151.101.129.69
151.101.1.69
151.101.193.69
151.101.65.6


Does the node request lib differ?

Answer

Your req object should have a connection object on it, which will have the remote address of the server you were connected to.

req.connection.remoteAddress

Of course, you need to wait until you actually have a connection, so I would just use the connect event which has what you need. Untested, but try this:

req.on('connect', (res, socket, head) => {
  console.log(socket.remoteAddress);
});

https://nodejs.org/api/net.html#net_socket_remoteaddress

Comments