lets say I've created a simple node.js TCP Socket server as follows.
var server = net.createServer(function (socket) {
socket.end("goodbye\n");
});
// listen on port 80, like a webserver would, and configured to accept connections to multiple hosts, ie test.example.com, sdfsdfsdf.example.com, example2.com.
server.listen(80, function() {
address = server.address();
console.log("opened server on %j", address);
});
server.on('connection', function(socket) {
//log('connection data', socket);
log('CONNECTED SOCKET DATA', socket.address());
log('CONNECTED LOCAL, %s:%s', socket.localAddress, socket.localPort);
log('CONNECTED %s:%s', socket.remoteAddress, socket.remotePort);
//How do I find the server hostname that the client connected to?
// eg test.example.com or example2.com
});
Once a tcp connection
is made, I want to parse the hostname that the client attempted to connect to. However the socket
does not seem to have this information.
The following is what I got when I ran the previous code (removed ip addresses)
CONNECTED SOCKET DATA { port: 80, family: 2, address: '[SERVER IP ADDRESS]' }
CONNECTED LOCAL, undefined:undefined
CONNECTED [CLIENT IP ADDRESS]:13263
I've gone through the nodejs socket documentation but I cant find anything related to host name. The documentation actually says that the socket.localAddress
will be an IP Address, with makes it useless in my case.
That information is not available at the TCP layer. You need to look at the Host
header at the HTTP
layer when a request arrives. This will be available as req.headers.host
when a request arrives. http://nodejs.org/docs/latest/api/all.html#all_message_headers
Also based on your comment, trying to run a non-HTTP server on port 80 is asking for trouble. You are going to get connections from web spiders and botnets all the time, so make sure your program properly handles HTTP clients connecting and disconnects them or perhaps sends an HTTP error message.
Joe is correct in the comment that if you are not using HTTP, your custom protocol will need to transmit the "virtual host" name from the client to the server in the first packet/header message of your custom protocol.