Search code examples
network-programmingnode.jstcpportlisten

How to listen to a random tcp socket in node.js


I know I can create a tcp server like that in node.js

var dataServer = net.createServer(function (stream) { 
}); 

dataServer.on("listening", function() { 
    // this data server listen to a random port 
    // but how can I get the number of port 
    console.log(dataServer.localPort) 
} 

dataServer.listen(0, '0.0.0.0'); 

But I don't know how to get the port number and send to another service.

Or I should find a random available port and pass to dataServer.listen?


Solution

  • You can find the address and port the server is listening on using the address method.

    dataServer.address();
    // => { address: '0.0.0.0', port: 49717 }