zoukankan      html  css  js  c++  java
  • 端口映射(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)
  • 相关阅读:
    Selenium自动化Chrome浏览器 在windows下窗口最大化
    Linux下的压缩解压缩命令详解及实例
    Windows下及Mac下的IntelliJ IDEA快捷键
    Missing artifact com.oracle:ojdbc6:jar:10.2.0.4.0问题解决 ojdbc包pom.xml出错
    使用cmd命令进行导入
    导入dmp文件时,需要删除原有ORACLE数据库实例
    HTML编码规范、CSS编码规范
    javascript函数与表达式
    JS中闭包、函数与对象的介绍和用法
    JS中typeof和instanceof用法区别
  • 原文地址:https://www.cnblogs.com/yizhipanghu/p/10901701.html
Copyright © 2011-2022 走看看