2014-02-10 44 views
4

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

+0

找到一个解决这个问题的解决方法。发布答案。 –

回答

1

套接字被分配一个本地端口。要重复使用相同的端口,可以使用与服务器通信所用的相同套接字连接到客户端。这适用于你,因为你正在做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}); 
}); 
-1

创建与公共服务器的连接后,您还需要听的是被用来建立连接完全相同的地方(!!)端口上。

我伸出你的testcode到概念的完整的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