在python中使用代理和多个套接字

时间:2018-12-21 11:36:31

标签: python sockets

我正在编写一个具有tcp连接的代理,该代理可以侦听来自客户端的多个端口并将其转发到服务器。

问题是该软件挂在sock.accept上。

也许我在这里做一个混乱的逻辑,但是我需要一个连接到PC的客户端,并且该PC连接到另一台设备。所以我写了那个小代理,然后在socket.accept()中收到无效的参数错误

import select
import socket
import threading

class Proxy(object):

    def __init__(self, ip, ports):
        self._ip = ip
        self._sockets = []
        self._proxy = {}

        for port in ports:
            self._proxy[port] = self.add_socket(port)

    def add_socket(self, port=None):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if port:
            # sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            sock.bind(('0.0.0.0',port))
        self._sockets.append(sock)
        return sock

    def get_client(self, src_sock, src_addr):
        src_ip, src_port = src_addr
        _, dst_port = src_sock.getsockname()

        if src_ip == self._ip:
            # got packet from device
            dst_addr = ("10.8.8.210", dst_port)
        else:
            # got packet from client
            dst_addr = self._ip, dst_port
            print(">", src_port, dst_addr)
        dst_sock = self._proxy[src_port]
        return dst_sock, dst_addr

    def run(self):
        while True:
            read_list, _, _ = select.select(self._sockets, [], [])

            if read_list:
                for sock in read_list:
                    try:

                        conn, addr = sock.accept()
                        data  = conn.recvfrom(16*2024)
                        # print("got data from {} {}".format(sock, addr))
                        dst_sock, dst_addr = self.get_client(sock, addr)
                       # print("forwarding data from {} to {}".format(addr, dst_addr, len(data)))
                        dst_sock.sendto(data, dst_addr)
                    except:
                        raise # pass # print("no recipient for data")
        for s in self._sockets:
             s.close()

ports = [30001,30002,30003, 30070, 30071,30072,30075]
p = Proxy("192.168.2.10", ports)                    
p.run()

1 个答案:

答案 0 :(得分:1)

您必须在listen之前在套接字上调用accept

sock.listen(1)之后将add_socket添加到bind

 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 sock.bind(('0.0.0.0', port))
 sock.listen(1)
 self._sockets.append(sock)

然后允许您调用没有错误的接受。您可能需要将监听积压设置为更大的数量。