【问题标题】:TCP hole punching in Node.jsNode.js 中的 TCP 打孔
【发布时间】:2014-03-08 02:03:50
【问题描述】:

我正在尝试通过 node.js 中的两个 NAT 打一个 TCP 漏洞。问题是我不知道如何选择连接应该使用哪个本地端口?

【问题讨论】:

  • 找到了解决此特定问题的解决方法。发布答案。

标签: node.js tcp ip hole-punching


【解决方案1】:

创建与公共服务器的连接后,您还需要侦听用于建立该连接的完全相同的本地 (!!) 端口。

我将您的测试代码扩展为完整的 tcp 打孔概念证明:

// server.js
var server = require('net').createServer(function (socket) {
    console.log('> Connect to this public endpoint with clientB:', socket.remoteAddress + ':' + socket.remotePort);
}).listen(4434, function (err) {
    if(err) return console.log(err);
    console.log('> (server) listening on:', server.address().address + ':' + server.address().port)
});

// clientA.js
var c = require('net').createConnection({host : 'PUBLIC_IP_OF_SERVER', port : 4434}, function () {
    console.log('> connected to public server via local endpoint:', c.localAddress + ':' + c.localPort);

    // do not end the connection, keep it open to the public server
    // and start a tcp server listening on the ip/port used to connected to server.js
    var server = require('net').createServer(function (socket) {
        console.log('> (clientA) someone connected, it\s:', socket.remoteAddress, socket.remotePort);
        socket.write("Hello there NAT traversal man, this is a message from a client behind a NAT!");
    }).listen(c.localPort, c.localAddress, function (err) {
        if(err) return console.log(err);
        console.log('> (clientA) listening on:', c.localAddress + ':' + c.localPort);
    });
});

// clientB.js
// read the server's output to find the public endpoint of A:
var c = require('net').createConnection({host : 'PUBLIC_IP_OF_CLIENT_A', port : PUBLIC_PORT_OF_CLIENT_A},function () {
    console.log('> (clientB) connected to clientA!');

    c.on('data', function (data) {
        console.log(data.toString());
    });
});

有关在服务器上发生信号的更完整版本,我在这里参考我的代码:https://github.com/SamDecrock/node-tcp-hole-punching

【讨论】:

    【解决方案2】:

    套接字被分配了一个本地端口。要重用相同的端口,您可以使用用于与服务器通信的相同套接字连接到客户端。这对您有用,因为您正在进行 TCP 打孔。但是,您不能自己选择端口。

    这是一些测试代码:

    // 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});
    });
    

    【讨论】:

      猜你喜欢
      • 2012-02-07
      • 2016-12-05
      • 2011-09-19
      • 2017-01-25
      • 2014-06-08
      • 2015-02-10
      • 1970-01-01
      • 2014-12-28
      • 2015-05-25
      相关资源
      最近更新 更多