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)
  • 相关阅读:
    MyEclipse for Spring 10.0: GWT 2.1 and Spring Scaffolding
    redis 协议
    Eclipse项目编译
    urlencode
    Firefox浏览器设置字符编码格式
    怎么从一台电脑的浏览器输入地址访问另一台电脑服务器(WAMP服务器已搭建,PHPSTORM装好了)...
    Tplink路由器怎么设置端口映射 内网端口映射听语音
    5.04 toArray()有一个问题须要解决一下
    WCF服务编程读书笔记(4):实例管理
    maven常用命令介绍
  • 原文地址:https://www.cnblogs.com/yizhipanghu/p/10901701.html
Copyright © 2011-2022 走看看