Python socket 模块,SO_REUSEADDR 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.SO_REUSEADDR

项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise
项目:charm-plumgrid-gateway    作者:openstack    | 项目源码 | 文件源码
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle
项目:sarafu    作者:pesaply    | 项目源码 | 文件源码
def interact(self):
        from telnetlib import Telnet

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        s.bind((self._revHost, self._revPort))
        s.listen(5)
        cli = s.accept()[0]
        s.close()
        print("[+] Got connect-back")

        t = Telnet()
        t.sock = cli
        t.interact()
项目:Static-UPnP    作者:nigelb    | 项目源码 | 文件源码
def setup_sockets(self):

    self.sockets = {}
    ip_addresses = get_interface_addresses(self.logger)

    self.ip_addresses = ip_addresses

    multi_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    multi_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    multi_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.ttl)

    for ip in ip_addresses:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        mreq=socket.inet_aton(self.address)+socket.inet_aton(ip)
        multi_sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        self.logger.info("Regestering multicast for: %s: %s"%(self.address, ip))
        sock.bind((ip, self.port))

        self.sockets[ip] = sock

    multi_sock.bind(("", self.port))
    self.socks = [self.sockets[x] for x in self.sockets.keys()]
    self.multi_sock = multi_sock
项目:CON-SAI    作者:SSL-Roots    | 项目源码 | 文件源码
def __init__(self, group_addr, port):
        bind_addr = '0.0.0.0'

        # Create a IPv4/UDP socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Avoid error 'Address already in use'.
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Construct a membership_request
        membership_request = socket.inet_aton(group_addr) + socket.inet_aton(bind_addr)

        # Send add membership request to socket
        self.sock.setsockopt(socket.IPPROTO_IP, 
                socket.IP_ADD_MEMBERSHIP, membership_request)

        # Bind the socket to an interfaces
        self.sock.bind((bind_addr, port))

        # Set non-blocking receiving mode
        self.sock.setblocking(False)

        self.publisher = rospy.Publisher('/raw_referee', std_msgs.msg.String, queue_size=10)
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def __init__(self, server_address):
        # Create a listening socket
        self.listen_socket = listen_socket = socket.socket(
            self.address_family,
            self.socket_type
        )
        # Allow to reuse the same address
        listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # Bind
        listen_socket.bind(server_address)
        # Activate
        listen_socket.listen(self.request_queue_size)
        # Get server host name and port
        host, port = self.listen_socket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)
        self.server_port = port
        # Return headers set by Web framework/Web application
        self.headers_set = []
项目:charm-swift-proxy    作者:openstack    | 项目源码 | 文件源码
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def set_reuse_addr(self):
        # try to re-use a server port if possible
        try:
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_REUSEADDR,
                self.socket.getsockopt(socket.SOL_SOCKET,
                                       socket.SO_REUSEADDR) | 1
                )
        except socket.error:
            pass

    # ==================================================
    # predicates for select()
    # these are used as filters for the lists of sockets
    # to pass to select().
    # ==================================================
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle
项目:ParadoxIP150v2    作者:Tertiush    | 项目源码 | 文件源码
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("localhost", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def __init__(self, ctx, sock=None):
        """Create SSL socket object

        @param ctx: SSL context
        @type ctx: OpenSSL.SSL.Context
        @param sock: underlying socket object
        @type sock: socket.socket
        """
        if sock is not None:
            self.socket = sock
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.__ssl_conn = SSL.Connection(ctx, self.socket)
        self.buf_size = self.__class__.default_buf_size
        self._makefile_refs = 0
项目:twampy    作者:nokia    | 项目源码 | 文件源码
def bind(self, addr, port, tos, ttl, df):
        log.debug(
            "bind(addr=%s, port=%d, tos=%d, ttl=%d)", addr, port, tos, ttl)
        self.socket = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, tos)
        self.socket.setsockopt(socket.SOL_IP,     socket.IP_TTL, ttl)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((addr, port))
        if df:
            if (sys.platform == "linux2"):
                self.socket.setsockopt(socket.SOL_IP, 10, 2)
            elif (sys.platform == "win32"):
                self.socket.setsockopt(socket.SOL_IP, 14, 1)
            elif (sys.platform == "darwin"):
                log.error("do-not-fragment can not be set on darwin")
            else:
                log.error("unsupported OS, ignore do-not-fragment option")
        else:
            if (sys.platform == "linux2"):
                self.socket.setsockopt(socket.SOL_IP, 10, 0)
项目:scroll_phat_hd-japanese-ticker    作者:moguno    | 项目源码 | 文件源码
def accept_thread():
    global channels

    serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversock.bind(("localhost", 39114))
    serversock.listen(10)

    while True:
        client_sock, client_address = serversock.accept()
        msg = client_sock.recv(8192).strip().decode("utf-8")

        data = msg.split("\t")
        channel = data[0]

        print(len(data))

        if len(data) <= 1:
            if channel in channels:
                del channels[channel]
        else:
            message = data[1]
            channels[channel] = message

        client_sock.close()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def set_reuse_addr(self):
        # try to re-use a server port if possible
        try:
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_REUSEADDR,
                self.socket.getsockopt(socket.SOL_SOCKET,
                                       socket.SO_REUSEADDR) | 1
                )
        except socket.error:
            pass

    # ==================================================
    # predicates for select()
    # these are used as filters for the lists of sockets
    # to pass to select().
    # ==================================================
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def listen(port=4444):
    global clisock, listening, done
    s   = socket(AF_INET, SOCK_STREAM)         
    s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)   
    s.bind(('0.0.0.0', port))                   
    s.listen(3)                                
    listening   = True
    sock, addr  = s.accept()                   
    clisock     = sock                         
    print("Client connected from {}".format(addr))
    data = ""
    while listening:
        try:
            rr, _, _ = select([sock,], [], [], 1) 
            if rr:
                data = sock.recv(1024)             
                print("{}".format(data), end="")   
        except:
            exit()
    print("Done listening.")
    done = True
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_create_server_sock(self):
        proto = asyncio.Future(loop=self.loop)

        class TestMyProto(MyProto):
            def connection_made(self, transport):
                super().connection_made(transport)
                proto.set_result(self)

        sock_ob = socket.socket(type=socket.SOCK_STREAM)
        sock_ob.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock_ob.bind(('0.0.0.0', 0))

        f = self.loop.create_server(TestMyProto, sock=sock_ob)
        server = self.loop.run_until_complete(f)
        sock = server.sockets[0]
        self.assertIs(sock, sock_ob)

        host, port = sock.getsockname()
        self.assertEqual(host, '0.0.0.0')
        client = socket.socket()
        client.connect(('127.0.0.1', port))
        client.send(b'xxx')
        client.close()
        server.close()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_create_server_addr_in_use(self):
        sock_ob = socket.socket(type=socket.SOCK_STREAM)
        sock_ob.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock_ob.bind(('0.0.0.0', 0))

        f = self.loop.create_server(MyProto, sock=sock_ob)
        server = self.loop.run_until_complete(f)
        sock = server.sockets[0]
        host, port = sock.getsockname()

        f = self.loop.create_server(MyProto, host=host, port=port)
        with self.assertRaises(OSError) as cm:
            self.loop.run_until_complete(f)
        self.assertEqual(cm.exception.errno, errno.EADDRINUSE)

        server.close()
项目:megadld    作者:arrase    | 项目源码 | 文件源码
def run(self):
        try:
            self._tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._tcpServer.bind((self._config.ip, self._config.port))
        except socket.error:
            self._log.error("There was an error when trying to bind the server")
            exit(2)
        finally:
            self._log.info("Waiting for connections ...")

        while True:
            self._tcpServer.listen(4)
            (conn, (ip, port)) = self._tcpServer.accept()
            newthread = DownloadThread(conn, self._config)
            newthread.start()
            self.threads.append(newthread)
项目:Fuk    作者:r4gnax    | 项目源码 | 文件源码
def server_loop():
    global target
    if  target == "0.0.0.0":
        log('w', "Listening interface not set, listening on all interfaces.")

    if ipv6:
        server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
    else:
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((target, port))
    server.listen(5)
    log('i', "Listening on %s:%i..." % (target, port))

    if not single:
        while True:
            client_sock, addr = server.accept()
            log('s', 'New connection from %s:%i !' % (addr[0], addr[1]))
            handler_thr=threading.Thread(target=client_handler, args=(client_sock,))
            handler_thr.daemon = True
            handler_thr.start()
    else:
        client_sock, addr = server.accept()
        log('s', 'New connection from %s:%i !' % (addr[0], addr[1]))
        client_handler(client_sock)
项目:Workshops    作者:HackSoftware    | 项目源码 | 文件源码
def echo_server(address):
    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Running several times with too small delay between executions,
    # could lead to: socket.error: [Errno 98] Address already in use
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # Associate the socket with the provided server address
    sock.bind(address)
    # Listen for incoming connections
    sock.listen(1)

    while True:
        # Wait for a connection
        connection, addr = sock.accept()
        # accept() returns an open connection between the server and client + the
        # address of the client. The connection is different socket on another port
        echo_handler(connection, addr)
项目:auto_proxy    作者:peablog    | 项目源码 | 文件源码
def run(self):
        try:
            logger.info('Starting server on port %d' % self.port)
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.bind((self.hostname, self.port))
            self.socket.listen(self.backlog)
            while True:
                conn, addr = self.socket.accept()
                logger.debug('Accepted connection %r at address %r' % (conn, addr))
                client = Client(conn, addr)
                self.handle(client)
        except Exception as e:
            logger.exception('Exception while running the server %r' % e)
        finally:
            logger.info('Closing server socket')
            self.socket.close()
项目:HTTPWookiee    作者:regilero    | 项目源码 | 文件源码
def _prepare_server_socket(self):
        try:
            self.inmsg(
                '# Connecting Listening socket to IP: {0} PORT: {1}'.format(
                    self.hostip, self.port))
            self.listen_sock = socket.socket(socket.AF_INET,
                                             socket.SOCK_STREAM)
            self.listen_sock.setsockopt(socket.SOL_SOCKET,
                                        socket.SO_REUSEADDR,
                                        1)
            self.listen_sock.bind((self.hostip, self.port))
            self.listen_sock.listen(self.queue)
            self.inmsg('# Start Listening with queue size {0}'.format(
                       self.queue))
        except socket.error as msg:
            self.inmsg("[ERROR] {0}".format(msg))
            raise Exception('error creating listening socket')
项目:Dshield    作者:ywjt    | 项目源码 | 文件源码
def get_free_ports(num_ports, ip='127.0.0.1'):
    """Get `num_ports` free/available ports on the interface linked to the `ip´
    :param int num_ports: The number of free ports to get
    :param str ip: The ip on which the ports have to be taken
    :return: a set of ports number
    """
    sock_ports = []
    ports = set()
    try:
        for _ in range(num_ports):
            sock = socket.socket()
            cur = [sock, -1]
            # append the socket directly,
            # so that it'll be also closed (no leaked resource)
            # in the finally here after.
            sock_ports.append(cur)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind((ip, 0))
            cur[1] = sock.getsockname()[1]
    finally:
        for sock, port in sock_ports:
            sock.close()
            ports.add(port)
    assert num_ports == len(ports)
    return ports
项目:shellsploit-framework    作者:Exploit-install    | 项目源码 | 文件源码
def listen(port=4444):
    global clisock, listening, done
    s   = socket(AF_INET, SOCK_STREAM)         
    s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)   
    s.bind(('0.0.0.0', port))                   
    s.listen(3)                                
    listening   = True
    sock, addr  = s.accept()                   
    clisock     = sock                         
    print("Client connected from {}".format(addr))
    data = ""
    while listening:
        try:
            rr, _, _ = select([sock,], [], [], 1) 
            if rr:
                data = sock.recv(1024)             
                print("{}".format(data), end="")   
        except:
            exit()
    print("Done listening.")
    done = True
项目:pixelvloed    作者:JanKlopper    | 项目源码 | 文件源码
def __init__(self, queue, options):
    """Init the pixelVloed server"""
    self.debug = options.debug if options.debug else False
    self.pixeloffset = 2
    self.fps = 30
    self.screen = None
    self.udp_ip = options.ip if options.ip else UDP_IP
    self.udp_port = options.port if options.port else UDP_PORT
    self.factor = options.factor if options.factor else 1
    self.canvas()
    self.set_title()
    self.queue = queue
    self.limit = options.maxpixels if options.maxpixels else MAX_PIXELS
    self.pixels = None
    self.broadcastsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.broadcastsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    self.broadcastsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
项目:pixelvloed    作者:JanKlopper    | 项目源码 | 文件源码
def __init__(self, queue, options):
    """Init the pixelVloed server"""
    self.debug = options.debug if options.debug else False
    self.pixeloffset = 2
    self.fps = 30
    self.screen = None
    self.udp_ip = options.ip if options.ip else UDP_IP
    self.udp_port = options.port if options.port else UDP_PORT
    self.factor = options.factor if options.factor else 1
    self.canvas()

    self.queue = queue
    self.limit = options.maxpixels if options.maxpixels else MAX_PIXELS
    self.pixels = None
    self.broadcastsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.broadcastsocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    self.broadcastsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
项目:charm-nova-compute    作者:openstack    | 项目源码 | 文件源码
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle
项目:charm-nova-compute    作者:openstack    | 项目源码 | 文件源码
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle
项目:swarm    作者:a7vinx    | 项目源码 | 文件源码
def _receive_master(self):
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        # incase 'Address already in use error'
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('',self._s_port))
        LOG.debug('listen on port:%d'%self._s_port)
        s.listen(1)
        sock, addr=s.accept()
        LOG.debug('receive from master host...')
        buff=''
        while True:
            d=sock.recv(4096)
            buff+=d
            if d.find('__EOF__')!=-1:
                break
        sock.send('ack')
        sock.close()
        s.close()
        # cut off last __EOF__
        buff=buff[:-7]
        # return to origin args
        buff=buff.replace('__EOF___','__EOF__')
        return buff
项目:SameKeyProxy    作者:xzhou    | 项目源码 | 文件源码
def runp (self):
        host = ''
        port = 20666
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((host,port))
        server.listen(1)
        while True:
            client, addr = server.accept ()
            if addr[0] != "127.0.0.1":
                client.send("Hacked By China!")
                client.close()
                continue
            request = client.recv(8192)
            request = request.split('\n')
            path = request[0].split()[1]
            client.send("HTTP/1.0 200 OK\r\n")
            client.send("Content-Type: text/html\r\n\r\n")
            if path == "/":
                client.send(json.dumps(self.sessions))
            client.close()
项目:SameKeyProxy    作者:xzhou    | 项目源码 | 文件源码
def runp (self):
        host = ''
        port = 20666
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((host,port))
        server.listen(1)
        while True:
            client, addr = server.accept ()
            if addr[0] != "127.0.0.1":
                client.send("Hacked By China!")
                client.close()
                continue
            request = client.recv(8192)
            request = request.split('\n')
            path = request[0].split()[1]
            client.send("HTTP/1.0 200 OK\r\n")
            client.send("Content-Type: text/html\r\n\r\n")
            if path == "/":
                client.send(json.dumps(self.sessions))
            client.close()
项目:SWProxy-plugins    作者:lstern    | 项目源码 | 文件源码
def run(self):
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            logger.info('Starting server on {}, port {}'.format(self.hostname, self.port))
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.bind((self.hostname, self.port))
            self.socket.listen(self.backlog)
            while True:
                conn, addr = self.socket.accept()
                logger.info('Accepted connection %r at address %r' % (conn, addr))
                client = Client(conn, addr)
                self.handle(client)
        except Exception as e:
            logger.exception('Exception while running the server %r' % e)
        finally:
            logger.info('Closing server socket')
            self.socket.close()
项目:CON-SAI    作者:SSL-Roots    | 项目源码 | 文件源码
def __init__(self, group_addr, port):
        bind_addr = '0.0.0.0'

        # Create a IPv4/UDP socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Avoid error 'Address already in use'.
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Construct a membership_request
        membership_request = socket.inet_aton(group_addr) + socket.inet_aton(bind_addr)

        # Send add membership request to socket
        self.sock.setsockopt(socket.IPPROTO_IP, 
                socket.IP_ADD_MEMBERSHIP, membership_request)

        # Bind the socket to an interfaces
        self.sock.bind((bind_addr, port))

        # Set non-blocking receiving mode
        self.sock.setblocking(False)

        self.publisher = rospy.Publisher('/raw_vision', std_msgs.msg.String, queue_size=10)
项目:wsproto    作者:python-hyper    | 项目源码 | 文件源码
def start_listener(host='127.0.0.1', port=8642, shutdown_port=8643):
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((host, port))
    server.listen(1)
    shutdown_server = socket.socket()
    shutdown_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    shutdown_server.bind((host, shutdown_port))
    shutdown_server.listen(1)

    done = False
    filenos = {s.fileno(): s for s in (server, shutdown_server)}

    while not done:
        r, _, _ = select.select(filenos.keys(), [], [], 0)

        for sock in [filenos[fd] for fd in r]:
            if sock is server:
                new_conn(server.accept()[0])
            else:
                done = True
项目:AshsSDK    作者:thehappydinoa    | 项目源码 | 文件源码
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2)
项目:esp32    作者:smeenka    | 项目源码 | 文件源码
def setup_conn(port, accept_handler):
    global listen_s
    listen_s = socket.socket()
    listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    ai = socket.getaddrinfo("0.0.0.0", port)
    addr = ai[0][4]

    listen_s.bind(addr)
    listen_s.listen(1)
    if accept_handler:
        listen_s.setsockopt(socket.SOL_SOCKET, 20, accept_handler)
    for i in (network.AP_IF, network.STA_IF):
        iface = network.WLAN(i)
        if iface.active():
            print("WebREPL daemon started on ws://%s:%d" % (iface.ifconfig()[0], port))
    return listen_s
项目:rpi3-webiopi    作者:thortex    | 项目源码 | 文件源码
def __init__(self, host, port, handler):
        threading.Thread.__init__(self, name="COAPThread")
        self.handler = COAPHandler(handler)
        self.host = host
        self.port = port
        self.multicast_ip = '224.0.1.123'
        if socket.has_ipv6:
            address_family = socket.AF_INET6
        else:
            address_family = socket.AF_INET
        try:
            self.socket = socket.socket(address_family, socket.SOCK_DGRAM)
        except:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(('', port))
        self.socket.settimeout(3)
        self.running = True
        self.start()
项目:MyPythonLib    作者:BillWang139967    | 项目源码 | 文件源码
def __init__(self, addr, port, logic):
        dbgPrint("\n-- __init__: start!")
        self.conn_state = {}
        self.listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
        self.listen_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.listen_sock.bind((addr, port))
        self.listen_sock.listen(10)
        self.setFd(self.listen_sock)
        self.epoll_sock = select.epoll()
        self.epoll_sock.register(self.listen_sock.fileno(), select.EPOLLIN)
        self.logic = logic
        self.sm = {
                   'accept': self.accept2read,
                   "read": self.read2process,
                   "write":self.write2read,
                   "process": self.process,
                   "closing": self.close,
                   }
项目:hologram-python    作者:hologram-io    | 项目源码 | 文件源码
def openReceiveSocket(self):

        self.__enforce_receive_host_and_port()

        if self.__to_use_at_sockets():
            self.network.open_receive_socket(self.receive_port)
            return True

        self._receive_cv.acquire()
        self._receive_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._receive_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.logger.info('Socket created')
        self._receive_cv.release()

        self.open_receive_socket_helper()

        return True

    # EFFECTS: Opens and binds an inbound socket connection.
项目:Python-Network-Programming-Cookbook-Second-Edition    作者:PacktPublishing    | 项目源码 | 文件源码
def echo_server(port):
    """ A simple echo server """
    # Create a TCP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Enable reuse address/port 
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Bind the socket to the port
    server_address = (host, port)
    print ("Starting up echo server  on %s port %s" % server_address)
    sock.bind(server_address)
    # Listen to clients, backlog argument specifies the max no. of queued connections
    sock.listen(backlog) 
    while True: 
        print ("Waiting to receive message from client")
        client, address = sock.accept() 
        data = client.recv(data_payload) 
        if data:
            print ("Data: %s" %data)
            client.send(data)
            print ("sent %s bytes back to %s" % (data, address))
        # end connection
        client.close()
项目:instax_api    作者:jpwsutton    | 项目源码 | 文件源码
def __init__(self, verbose=False, log=None, host='0.0.0.0', port=8080,
                 dest="images", battery=2, remaining=10, total=20):
        """Initialise Server."""
        self.packetFactory = PacketFactory()
        self.host = host
        self.verbose = verbose
        self.log = log
        self.dest = dest
        self.port = port
        self.backlog = 5
        self.returnCode = Packet.RTN_E_RCV_FRAME
        self.ejecting = 0
        self.battery = battery
        self.printCount = total
        self.remaining = remaining
        self.running = True
        self.finished = False
        self.messageLog = []
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((self.host, self.port))
        signal.signal(signal.SIGINT, self.signal_handler)
        self.imageMap = {}
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def __init__(self):
        self.tcpPort = 31337
        self.tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.tcpsocket.bind(("0.0.0.0", self.tcpPort))
        self.tcpsocket.listen(10)

        self.discoverysocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.discoverysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.discoverysocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

        self.glfwWorkers = {}

        self.controllerConn = None
        self.controllerAddr = None
        self.outbuf = ""    # IO buffer for controller
        self.inbuf = ""

        self.monitors = glfw.get_monitors()

        for monitor in glfw.get_monitors():
            self.glfwWorkers[bytes.decode(glfw.get_monitor_name(monitor))] = glfwWorker(monitor)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def __init__(self):
        self.port = 31337
        self.tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.tcpsocket.bind(("127.0.0.1", self.port))
        self.tcpsocket.listen(10)

        self.udpsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.udpsock.bind(("127.0.0.1", 9050))

        self.messageBuf = ""
        self.outBuf = ""

        self.controllerConn = None
        self.controllerAddr = None

        self.glfwWorkers = {}  # Associate monitor-names with glfw workers

        self.monitors = []
        self.monitornames = []  # TODO: Reduce to monitorDict
        self.monitorDict = {}
        self.glfwMonitorCallback()  # Retrieve current monitors
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def listen(self):
        s=None
        if not self.hostname:
            self.hostname=None
        last_exc=None
        for res in socket.getaddrinfo(self.hostname, self.port, socket.AF_UNSPEC, socket.SOCK_DGRAM, 0, socket.AI_PASSIVE):
            af, socktype, proto, canonname, sa = res
            try:
                s = socket.socket(af, socktype, proto)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            except socket.error as msg:
                s = None
                last_exc=msg
                continue
            try:
                s.bind(sa)
            except socket.error as msg:
                s.close()
                s = None
                last_exc=msg
                continue
            break
        self.sock=s
        if self.sock is None:
            raise last_exc
项目:dbus-mqtt    作者:victronenergy    | 项目源码 | 文件源码
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2)