How does Node.js choose random ports?

前端 未结 2 1239
你的背包
你的背包 2020-12-29 10:32

With Node.js, we can create a server and listen on a random port:

var server = net.createServer();
server.listen(0, \'127.0.0.1\');

The fir

2条回答
  •  遥遥无期
    2020-12-29 11:03

    The OS assigns the port number. See https://github.com/joyent/node/blob/v0.6.11/lib/net.js#L780-783

    On OS X, the assignment is sequential, userland and does not check the port to verify it is not in use.

    On Ubuntu 11.04, the assignment is random, userland and also does not check if port is in use.

    The script below can be used to test on other platforms. To verify the ports are userland, I ran the script 10,000 times via bash piped to grep -c "port: [0-9]{1,3}" with zero matches.

    var net = require('net'),
        firstPort;
    
    (function createServer(port) {
      var server = net.createServer();
      server.listen(port, function() {
        address = server.address();
        if (port === 0) { 
          if (firstPort === undefined) {
            firstPort = address.port;
            // cause a EADDRINUSE in 10 more sockets for sequential platforms
            // without this, will run out of fd's before hitting EADDRINUSE
            createServer(firstPort + 10); 
            console.log('addr in use port trap: ', firstPort + 10);
          } else {
            // on OS X (sequential) this will increment the OS's sequential counter
            // and not cause EADDRINUSE
            createServer(address.port + 1);
          }
          createServer(0);
        }
        console.log("requested port:", port, " binded port:",address.port);
      });  
    })(0);
    

提交回复
热议问题