2014-02-10 48 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