Search code examples
node.jstcpiphole-punching

TCP hole punching in Node.js


I'm trying to punch a TCP hole through two NATs in node.js. The problem is I can't figure out how to choose which local port the connection should use?


Solution

  • The socket is assigned a local port. To reuse the same port you can connect to the client using the same socket that was used to communicate with the server. This works for you because you are doing TCP hole punching. However, you cannot choose a port yourself.

    Here is some test code:

    // server.js
    require('net').createServer(function(c) {
        c.write(c.remotePort.toString(10));
    }).listen(4434);
    
    
    //client.js
    var c = require('net').createConnection({host : '127.0.0.1', port : 4434});
    c.on('data', function(data) {
        console.log(data.toString(), c.localPort);
        c.end();
    });
    
    c.on('end', function() {
        c.connect({host : '127.0.0.1', port : 4434});
    });