• 端口映射(socket应用)


    # coding=gb2312
    
    import sys
    import time
    import socket
    import thread
    import subprocess
    
    ################################
    
    interfaceName = "本地连接"
    portStart = 10000
    portNumber = 500
    
    ################################
    
    def getNextIp(ip):
        t = [int(x) for x in ip.split(".")]
        assert len(t) == 4
        t[3] += 1
        for i in range(3, -1, -1):
            if t[i] > 255:
                assert i > 0
                t[i] = 1
                t[i - 1] += 1
            else:
                break
        return ".".join([str(x) for x in t])
    
    def print_with_lock(msg):
        lock.acquire()
        print msg
        lock.release()
    
    def server(listen_host, listen_port, target_host, target_port):
        print_with_lock("server started, %s, %s, %s, %s" % (listen_host, listen_port, target_host, target_port))
        try:
            dock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            dock_socket.bind((listen_host, listen_port))
            dock_socket.listen(5)
            while True:
                client_socket, client_address = dock_socket.accept()
                print_with_lock("connection accepted, %s, %s, %s, %s" % (listen_host, listen_port, target_host, target_port))
                server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                server_socket.connect((target_host, target_port))
                thread.start_new_thread(forward, (client_socket, server_socket, "client -> server" ))
                thread.start_new_thread(forward, (server_socket, client_socket, "server -> client" ))
        finally:
            thread.start_new_thread(server, (listen_host, listen_port, target_host, target_port))
    
    def forward(source, destination, description):
        data = 'dummy'
        while data:
            data = source.recv(1024)
            if data:
                destination.sendall(data)
            else:
                source.shutdown(socket.SHUT_RD)
                destination.shutdown(socket.SHUT_WR)
    
    
    
    lock = thread.allocate_lock()
    
    # 启动代理线程
    port = portStart
    ipin = "127.0.0.2"
    for i in range(0, portNumber):
        thread.start_new_thread(server, ("0.0.0.0", port, ipin, 23))
        ipin = getNextIp(ipin)
        port += 1
    
    while True:
        time.sleep(1.0)
  • 相关阅读:
    druid:阿里巴巴开源,数据库连接池管理
    各JAVA开发框架版本及对应信息
    各版本区别
    MyBatis 知识点
    java的关键字:static、final
    请求转发(Forward)和重定向(Redirect)的区别
    Spring 向页面传值以及接受页面传过来的参数的方式
    Spring 框架中 ModelAndView、Model、ModelMap 的区别
    Connection: keep-alive,Content-Length,Transfer-Encoding: chunked,Content-Encoding: gzip等
    git 报错及解决
  • 原文地址:https://www.cnblogs.com/yizhipanghu/p/10901701.html
Copyright © 2020-2023  润新知