I have 3 simple NodeJS servers usign NET, HTTP and UDP. Each server listens on port X but has multiple IP addresses. I would like to retrive the actual IP address of the server when the client connects to the server (the IP to where the client connected, the IP that client had to write to connect to the server).
var httpService = http.createServer(function(req, res){
req.getActualServerAddress();
});
httpService.listen(8000);
var netService = net.createServer(function(socket) {
socket.getActualServerAddress();
});
netService.listen(8001);
var udpService = dgram.createSocket("udp4");
udpService.on("message", function (msg, rinfo){
开发者_如何学编程 rinfo.getActualServerAddress();
});
udpService.bind(8002);
Thx.
If you do not specify the hostname, the server will start at 0.0.0.0. So you may not get your desired outcome[ read Maqurading]. For HTTP you can use the HTTP "Host" header [mandatory since HTTP/1.1] which might be fruitful for your case.
Still you may give a try with:
socket.address()
Returns the bound address and port of the socket as reported by the operating system. Returns an object with two properties, e.g. {"address":"192.168.57.1", "port":62053}
Here is a sample for tcp:
var netService = require('net').createServer(function(socket) {
address = netService.address();
console.log("Stream on %j", socket.address());
console.log("opened server on %j", address);
});
netService.listen(8001);
Sample for http:
var httpService = require('http').createServer(function(req, res){
console.log("Stream on %j", req.connection.address());
res.end("Hi");
});
httpService.listen(8000);
精彩评论