Node.js - forward all traffic from port A to port B

后端 未结 3 1437
小鲜肉
小鲜肉 2020-12-02 17:29

I\'m trying to forward all traffic from port 6999 to port 7000 (I know I could use iptables, but the idea is to use Node.js to do some packet inspection).

Here is th

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 18:20

    Here's my go at it:

    Supports giving the "from" and "to" from command line, and supports remote machines.

    var net = require('net');
    
    // parse "80" and "localhost:80" or even "42mEANINg-life.com:80"
    var addrRegex = /^(([a-zA-Z\-\.0-9]+):)?(\d+)$/;
    
    var addr = {
        from: addrRegex.exec(process.argv[2]),
        to: addrRegex.exec(process.argv[3])
    };
    
    if (!addr.from || !addr.to) {
        console.log('Usage:  ');
        return;
    }
    
    net.createServer(function(from) {
        var to = net.createConnection({
            host: addr.to[2],
            port: addr.to[3]
        });
        from.pipe(to);
        to.pipe(from);
    }).listen(addr.from[3], addr.from[2]);
    

    (save as proxy.js)

    To forward from localhost:9001 => localhost:80

    $ node proxy.js 9001 80
    

    Or localhost:9001 => otherhost:80

    $ node proxy.js 9001 otherhost:80
    

    (This was based on Andrey's answer, thanks!)

提交回复
热议问题