Python socket.SO_REUSEADDR() Examples

The following are code examples for showing how to use socket.SO_REUSEADDR(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: sarafu   Author: pesaply   File: donot.py    (MIT License) View Source Project 9 votes vote down vote up
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() 
Example 2
Project: esp32   Author: smeenka   File: webrepl.py    (license) View Source Project 9 votes vote down vote up
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 
Example 3
Project: pycos   Author: pgiri   File: chat_server.py    (license) View Source Project 8 votes vote down vote up
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 
Example 4
Project: Static-UPnP   Author: nigelb   File: util.py    (license) View Source Project 8 votes vote down vote up
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 
Example 5
Project: charm-plumgrid-gateway   Author: openstack   File: rpdb.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
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 
Example 6
Project: CON-SAI   Author: SSL-Roots   File: multicast.py    (license) View Source Project 7 votes vote down vote up
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) 
Example 7
Project: pycos   Author: pgiri   File: chat_server.py    (license) View Source Project 6 votes vote down vote up
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 
Example 8
Project: python-   Author: secondtonone1   File: webserver.py    (license) View Source Project 6 votes vote down vote up
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 = [] 
Example 9
Project: kinect-2-libras   Author: inessadl   File: asyncore.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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().
    # ================================================== 
Example 10
Project: charm-keystone   Author: openstack   File: rpdb.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 11
Project: charm-keystone   Author: openstack   File: rpdb.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 12
Project: charm-keystone   Author: openstack   File: rpdb.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 13
Project: charm-keystone   Author: openstack   File: rpdb.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 14
Project: ParadoxIP150v2   Author: Tertiush   File: client.py    (Eclipse Public License 1.0) View Source Project 6 votes vote down vote up
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) 
Example 15
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: ssl_socket.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 16
Project: twampy   Author: nokia   File: twampy.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
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) 
Example 17
Project: scroll_phat_hd-japanese-ticker   Author: moguno   File: ticker.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 18
Project: hostapd-mana   Author: adde88   File: asyncore.py    (license) View Source Project 6 votes vote down vote up
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().
    # ================================================== 
Example 19
Project: purelove   Author: hucmosin   File: netcat_hander.py    (license) View Source Project 6 votes vote down vote up
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 
Example 20
Project: annotated-py-asyncio   Author: hhstore   File: test_events.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 21
Project: annotated-py-asyncio   Author: hhstore   File: test_events.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 22
Project: megadld   Author: arrase   File: server.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 23
Project: Fuk   Author: r4gnax   File: netfuk.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 24
Project: Workshops   Author: HackSoftware   File: secho.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 25
Project: auto_proxy   Author: peablog   File: proxy_server.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 26
Project: HTTPWookiee   Author: regilero   File: server.py    (license) View Source Project 6 votes vote down vote up
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') 
Example 27
Project: Dshield   Author: ywjt   File: misc.py    (license) View Source Project 6 votes vote down vote up
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 
Example 28
Project: shellsploit-framework   Author: Exploit-install   File: netcat.py    (license) View Source Project 6 votes vote down vote up
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 
Example 29
Project: pixelvloed   Author: JanKlopper   File: vloed.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 30
Project: pixelvloed   Author: JanKlopper   File: sdlvloed.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 31
Project: charm-nova-compute   Author: openstack   File: rpdb.py    (license) View Source Project 6 votes vote down vote up
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 
Example 32
Project: charm-nova-compute   Author: openstack   File: rpdb.py    (license) View Source Project 6 votes vote down vote up
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 
Example 33
Project: swarm   Author: a7vinx   File: sswarm.py    (license) View Source Project 6 votes vote down vote up
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 
Example 34
Project: SameKeyProxy   Author: xzhou   File: session_hijack.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 35
Project: SameKeyProxy   Author: xzhou   File: session_hijack.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 36
Project: SWProxy-plugins   Author: lstern   File: proxy.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 37
Project: CON-SAI   Author: SSL-Roots   File: multicast.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 38
Project: wsproto   Author: python-hyper   File: test_server.py    (license) View Source Project 6 votes vote down vote up
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 
Example 39
Project: AshsSDK   Author: thehappydinoa   File: client.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 40
Project: rpi3-webiopi   Author: thortex   File: coap.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 41
Project: MyPythonLib   Author: BillWang139967   File: NetBase.py    (license) View Source Project 6 votes vote down vote up
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,
                   } 
Example 42
Project: hologram-python   Author: hologram-io   File: CustomCloud.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 43
Project: Python-Network-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: 1_13a_echo_server.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 44
Project: instax_api   Author: jpwsutton   File: testServer.py    (license) View Source Project 6 votes vote down vote up
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 = {} 
Example 45
Project: pyree-old   Author: DrLuke   File: worker.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 46
Project: pyree-old   Author: DrLuke   File: workerOld.py    (license) View Source Project 6 votes vote down vote up
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 
Example 47
Project: pupy   Author: ru-faraon   File: servers.py    (license) View Source Project 6 votes vote down vote up
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 
Example 48
Project: dbus-mqtt   Author: victronenergy   File: client.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 49
Project: Arduino_Semi-Tesla   Author: jpdik   File: udpc.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, familiaIP=socket.AF_INET):
		self.ip = ""
		self.porta = 8000

		self.seqnum = 0

		self.packet = ""

		self.familiaIP = familiaIP
		self.protocolo = socket.SOCK_DGRAM

		self.sock = socket.socket(self.familiaIP, self.protocolo)

		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

	#essa função é chamada pelo cliente para realizar a conexao de seu socket 
Example 50
Project: python-broadlink   Author: mjg59   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, host, mac, timeout=10):
    self.host = host
    self.mac = mac
    self.timeout = timeout
    self.count = random.randrange(0xffff)
    self.key = bytearray([0x09, 0x76, 0x28, 0x34, 0x3f, 0xe9, 0x9e, 0x23, 0x76, 0x5c, 0x15, 0x13, 0xac, 0xcf, 0x8b, 0x02])
    self.iv = bytearray([0x56, 0x2e, 0x17, 0x99, 0x6d, 0x09, 0x3d, 0x28, 0xdd, 0xb3, 0xba, 0x69, 0x5a, 0x2e, 0x6f, 0x58])
    self.id = bytearray([0, 0, 0, 0])
    self.cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.cs.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    self.cs.bind(('',0))
    self.type = "Unknown"
    self.lock = threading.Lock()

    if 'pyaes' in sys.modules:
        self.encrypt = self.encrypt_pyaes
        self.decrypt = self.decrypt_pyaes
    else:
        self.encrypt = self.encrypt_pycrypto
        self.decrypt = self.decrypt_pycrypto