如何重用一個端口實現幾個不同的服務

如何重用一個端口實現幾個不同的服務

目的

有時候我們想暴露一個端口,實現不同的服務。不同的客戶端連過來之後,根據他們發過來的數據包智能確定用哪一個服務

本質上是我們實現一個監聽服務,根據發過來的第一個數據包區分協議類型,將之後的所有數據轉發給相應服務

要求

這個想法要求該服務必須是client先發送第一個數據包,有些服務是server先發送數據包就不能支持了

測試:看看哪些服務能支持到

把echo server改了一下,改成print出client的message即可

代碼如下

import socket

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            print(data)
            #conn.sendall(data)

測試過幾個協議,數據如下

// vnc
NA
    
// rdp
b'\x03\x00\x00\x13\x0e\xe0\x00\x00\x00\x00\x00\x01\x00\x08\x00\x0b\x00\x00\x00'

// socks
b'\x05\x02\x02\x00'
    
// http connect proxy
b'CONNECT xxx:5900 HTTP/1.1\r\nHost: xx:5900\r\nDate: Wed, 10 Mar 2021 05:44:47 GMT\r\nProxy-Connection: keep-alive\r\nUser-Agent: vncviewer/6.1.1 (Windows NT 10.0; x64; en_US)\r\nContent-Length: 0\r\n\r\n'

數據轉發服務

在網上找到一個node的代碼,經實驗功能ok

C:\Users\my\Downloads\node-port-mux-master>node example.js
Muxer listening on :::3000
2021-03-10T05:59:20.623Z - connection from ::ffff:10.0.120.72
2021-03-10T06:24:52.632Z - connection from ::ffff:10.1.1.66
2021-03-10T06:24:52.657Z - connection from ::ffff:10.1.1.66

example.js代碼如下

var Muxer = require('port-mux');

// start HTTP server on port 3001
require('http').createServer(function(req, res) {
  res.end('hello world from HTTP');
}).listen(3001);


// configure and start muxer
Muxer()
  // forward HTTP to port 3001
  .addRule(/^(?:GET|POST|PUT|DELETE)\s/, 3001, function(proxy, conn) {
    var addr = proxy.address();
    console.log('Incoming connection from %s passed to %s:%s',
      conn.remoteAddress,
      addr.address,
      addr.port
    );
  })
  // rdp
  .addRule(/^\x03\x00/, 3389)
  //socks proxy
  .addRule(/^\x05\x02/, 3389)
  // http proxy
  .addRule(/^CONNECT /, 3389)
  // forward HTTPS to port 3002
  .addRule(/^\x16\x03[\x00-\x03]/, 3002)
  // start listening; .listen() accepts the same arguments as net.Server#listen()
  .listen(3000, function() {
    var addr = this.address();
    console.warn('Muxer listening on %s:%s', addr.address, addr.port);
  })
  // .listen() returns the net.Server instance, so we can attach event handlers
  .on('connection', function(conn) {
    console.log('%s - connection from %s', new Date(), conn.remoteAddress);
  });

// Check the results with curl:
//
// $ curl http://localhost:3000/
// hello world from HTTP
// $ curl -k https://localhost:3000/
// hello world from HTTPS

Powered by Jekyll and Theme by solid

本站总访问量