Python socket.SOL_SOCKET() Examples

The following are code examples for showing how to use socket.SOL_SOCKET(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: micropython-barebones   Author: reapzor   File: webrepl.py    MIT License 7 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 2
Project: micropython-barebones   Author: reapzor   File: webrepl.py    MIT License 7 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: fs_image   Author: facebookincubator   File: common.py    MIT License 6 votes vote down vote up
def recv_fds(sock, msglen, maxfds, inheritable=False):
    '''
    Receives via a Unix domain socket a message of at most `msglen` bytes,
    with at most `maxfds` file descriptors in the ancillary data.  The file
    descriptors will be marked O_CLOEXEC unless inheritable is set to False.
    '''
    fds = array.array('i')
    msg, ancdata, msg_flags, _addr = sock.recvmsg(
        msglen, maxfds * socket.CMSG_SPACE(fds.itemsize),
        0 if inheritable else socket.MSG_CMSG_CLOEXEC,
    )
    assert not (msg_flags & socket.MSG_TRUNC), msg_flags
    assert not (msg_flags & socket.MSG_CTRUNC), msg_flags
    assert not (msg_flags & socket.MSG_ERRQUEUE), msg_flags
    for cmsg_level, cmsg_type, cmsg_data in ancdata:
        assert cmsg_level == socket.SOL_SOCKET, cmsg_level
        assert cmsg_type == socket.SCM_RIGHTS, cmsg_type
        assert len(cmsg_data) % fds.itemsize == 0, cmsg_data
        fds.frombytes(cmsg_data)
    return msg, list(fds)


# Don't wait forever if the `send_fds` side crashes.  This is 2.5 minutes so
# we still make progress on overloaded hosts. 
Example 4
Project: pyblish-win   Author: pyblish   File: asyncore.py    GNU Lesser General Public License v3.0 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 5
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testRDM(self):
        srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
        cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)

        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
                TIPC_LOWER, TIPC_UPPER)
        srv.bind(srvaddr)

        sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
                TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0)
        cli.sendto(MSG, sendaddr)

        msg, recvaddr = srv.recvfrom(1024)

        self.assertEqual(cli.getsockname(), recvaddr)
        self.assertEqual(msg, MSG) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_quick_connect(self):
        # see: http://bugs.python.org/issue10340
        server = TCPServer()
        t = threading.Thread(target=lambda: asyncore.loop(timeout=0.1, count=500))
        t.start()
        self.addCleanup(t.join)

        for x in xrange(20):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(.2)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
                         struct.pack('ii', 1, 0))
            try:
                s.connect(server.address)
            except socket.error:
                pass
            finally:
                s.close() 
Example 7
Project: pyblish-win   Author: pyblish   File: connection.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, address, family, backlog=1):
        self._socket = socket.socket(getattr(socket, family))
        try:
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._socket.setblocking(True)
            self._socket.bind(address)
            self._socket.listen(backlog)
            self._address = self._socket.getsockname()
        except socket.error:
            self._socket.close()
            raise
        self._family = family
        self._last_accepted = None

        if family == 'AF_UNIX':
            self._unlink = Finalize(
                self, os.unlink, args=(address,), exitpriority=0
                )
        else:
            self._unlink = None 
Example 8
Project: UR5_Controller   Author: tsinghua-rll   File: rtif.py    MIT License 6 votes vote down vote up
def connect(self):
        if self.__sock:
            return

        self.__buf = ''

        try:
            self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.__sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            self.__sock.setblocking(DEFAULT_TIMEOUT)
            self.__sock.connect((self.hostname, self.port))
            self.__conn_state = ConnectionState.CONNECTED
        except (socket.timeout, socket.error):
            self.__sock = None
            raise 
Example 9
Project: RF-Monitor   Author: EarToEarOak   File: server.py    GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, eventHandler):
        threading.Thread.__init__(self)
        self.name = 'Server'
        self.daemon = True
        self._eventHandler = eventHandler

        self._client = None
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        try:
            self._server.bind(('', PORT))
            self._server.listen(5)
        except socket.error:
            event = Event(Events.SCAN_ERROR, msg='Could not start server')
            post_event(eventHandler, event)
            return

        self._cancel = False
        self.start() 
Example 10
Project: kvmd   Author: pikvm   File: wol.py    GNU General Public License v3.0 6 votes vote down vote up
def __inner_wakeup(self) -> None:
        logger = get_logger(0)
        logger.info("Waking up %s (%s:%s) using Wake-on-LAN ...", self.__mac, self.__ip, self.__port)
        sock: Optional[socket.socket] = None
        try:
            # TODO: IPv6 support: http://lists.cluenet.de/pipermail/ipv6-ops/2014-September/010139.html
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            sock.connect((self.__ip, self.__port))
            sock.send(self.__magic)
        except Exception:
            logger.exception("Can't send Wake-on-LAN packet")
        else:
            logger.info("Wake-on-LAN packet sent")
        finally:
            if sock:
                try:
                    sock.close()
                except Exception:
                    pass 
Example 11
Project: deep-nn-car   Author: scope-lab-vu   File: controller.py    MIT License 6 votes vote down vote up
def liveStreamThread(stop_event, j):
    global setSpeed
    logging.basicConfig(filename='scheduler.log', level=logging.DEBUG, filemode='w')
    sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    sock2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock2.connect((server_address[0], liveStreamPort))
    sock2.settimeout(10)
    nullEvents = 0
    while not stop_event.is_set() and nullEvents < 20:
        dcTuple = j.get_dcTuple()
        (nullEvents) = Client.liveStreamReceiver(sock2, dcTuple, nullEvents)
    sock2.close()


# plotVelocity
# Creates a thread event that displays a dynamic plot of the speed. 
Example 12
Project: deep-nn-car   Author: scope-lab-vu   File: video2image.py    MIT License 6 votes vote down vote up
def liveStreamCamera(stop_event):
    sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM,0)
    sock2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock2.bind(server_address)
    sock2.listen(1)
    cap = configureCamera(320,240,50)
    ret = True
    connection,client_address = sock2.accept()
    while ret and not stop_event.is_set():
        # save frame as JPEG file
        ret, frame = cap.read()
        data = cv2.imencode('.jpg', frame)[1].tostring()
        size = str(sys.getsizeof(data))
        connection.sendall(size.encode())
        connection.sendall(data)
        connection.recv(10)
    release(cap)
    sock2.close() 
Example 13
Project: deep-nn-car   Author: scope-lab-vu   File: Webcam.py    MIT License 6 votes vote down vote up
def liveStreamCamera(stop_event):
    sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM,0)
    sock2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock2.bind(liveStreamServerAddress)
    sock2.listen(1)
    cap = configureCamera(320,240,30)
    ret = True
    connection,client_address = sock2.accept()
    while ret and not stop_event.is_set():
        # save frame as JPEG file
        ret, frame = cap.read()
        #frame = frame[0:239,0:319]
        frame = cv2.resize(frame,(200,66))
        data = cv2.imencode('.jpg', frame)[1].tostring()
        size = str(sys.getsizeof(data))
        connection.sendall(size.encode())
        connection.recv(16)
        connection.sendall(data)
        connection.recv(10)
    release(cap)
    sock2.close() 
Example 14
Project: deep-nn-car   Author: scope-lab-vu   File: Webcam.py    MIT License 6 votes vote down vote up
def liveStreamCamera(stop_event):
    sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM,0)
    sock2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock2.bind(liveStreamServerAddress)
    sock2.listen(1)
    cap = configureCamera(320,240,30)
    ret = True
    connection,client_address = sock2.accept()
    while ret and not stop_event.is_set():
        # save frame as JPEG file
        ret, frame = cap.read()
        #frame = frame[0:239,0:319]
        frame = cv2.resize(frame,(200,66))
        data = cv2.imencode('.jpg', frame)[1].tostring()
        size = str(sys.getsizeof(data))
        connection.sendall(size.encode())
        connection.recv(16)
        connection.sendall(data)
        connection.recv(10)
    release(cap)
    sock2.close() 
Example 15
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_wsgi.py    Apache License 2.0 6 votes vote down vote up
def test_socket_options_for_simple_server(self):
        # test normal socket options has set properly
        self.flags(tcp_keepidle=500, group='wsgi')
        server = nova.wsgi.Server("test_socket_options", None,
                                  host="127.0.0.1", port=0)
        server.start()
        sock = server._socket
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR))
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE))
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertEqual(CONF.wsgi.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        server.stop()
        server.wait() 
Example 16
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_wsgi.py    Apache License 2.0 6 votes vote down vote up
def test_socket_options_for_ssl_server(self):
        # test normal socket options has set properly
        self.flags(tcp_keepidle=500, group='wsgi')
        server = nova.wsgi.Server("test_socket_options", None,
                                  host="127.0.0.1", port=0,
                                  use_ssl=True)
        server.start()
        sock = server._socket
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR))
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE))
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertEqual(CONF.wsgi.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        server.stop()
        server.wait() 
Example 17
Project: XFLTReaT   Author: earthquake   File: UDP_generic.py    MIT License 6 votes vote down vote up
def serve(self):
		server_socket = None
		try:
			common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			whereto = (self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport")))
			server_socket.bind(whereto)
			self.comms_socket = server_socket
			self.serverorclient = 1
			self.authenticated = False

			self.communication_initialization()
			self.communication(False) 
			
		except KeyboardInterrupt:

			self.cleanup()
			return

		self.cleanup()

		return 
Example 18
Project: python-lifx-sdk   Author: smarthall   File: network.py    MIT License 6 votes vote down vote up
def __init__(self, address='0.0.0.0', broadcast='255.255.255.255'):
        # Prepare a socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.bind((address, 0))

        self._socket = sock

        self._listener = ListenerThread(sock, self._handle_packet)
        self._listener.start()

        self._packet_handlers = {}

        self._current_handler_id = 0

        self._broadcast = broadcast 
Example 19
Project: micropython-barebones   Author: reapzor   File: webrepl.py    MIT License 6 votes vote down vote up
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    prev = uos.dupterm(None)
    uos.dupterm(prev)
    if prev:
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws) 
Example 20
Project: micropython-barebones   Author: reapzor   File: webrepl.py    MIT License 6 votes vote down vote up
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    prev = uos.dupterm(None)
    uos.dupterm(prev)
    if prev:
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = uwebsocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws) 
Example 21
Project: AshsSDK   Author: thehappydinoa   File: client.py    MIT License 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 22
Project: InsightAgent   Author: insightfinder   File: script_runner.py    Apache License 2.0 6 votes vote down vote up
def acceptThread(parameters):
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(parameters['listenPort'])))
    acceptor.listen(5)
    cur_thread = threading.current_thread()
    logger.info("Listening to connections on port " + str(parameters['listenPort']) + '\n')

    while True:
        (clientSock, clientAddr) = acceptor.accept()
        print "==== Output Request ====="
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        logger.info(msg)
        thread3 = threading.Thread(target=sendFile, args=(clientSock, parameters))
        thread3.daemon = True
        thread3.start()
    acceptor.close()
    return 
Example 23
Project: InsightAgent   Author: insightfinder   File: reporting_send.py    Apache License 2.0 6 votes vote down vote up
def acceptThread():       
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(uploadPort)))
    acceptor.listen(5)
        
    cur_thread=threading.current_thread()
    while True:            
        (clientSock,clientAddr)=acceptor.accept()
        print "====Output Request:"
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        print msg
        thread3=threading.Thread(target=sendFile(clientSock))
        thread3.daemon=True
        thread3.start()
        #thread3.join()            
    acceptor.close()
    return 
Example 24
Project: CVE-2018-7750   Author: jm33-m0   File: sample_ssh_server.py    GNU General Public License v3.0 6 votes vote down vote up
def listener():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', 2222))

    sock.listen(100)
    client, addr = sock.accept()

    t = paramiko.Transport(client)
    t.set_gss_host(socket.getfqdn(""))
    t.load_server_moduli()
    t.add_server_key(host_key)
    server = Server()
    t.start_server(server=server)

    # Wait 30 seconds for a command
    server.event.wait(30)
    t.close() 
Example 25
Project: EvilOSX   Author: cys3c   File: Server.py    GNU General Public License v3.0 6 votes vote down vote up
def start_server(port):
    # Start the server
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('', port))
    server_socket.listen(128)  # Maximum connections Mac OSX can handle.

    status_messages.append(MESSAGE_INFO + "Successfully started the server on port {0}.".format(str(port)))
    status_messages.append(MESSAGE_INFO + "Waiting for clients...")

    while True:
        client_connection, client_address = ssl.wrap_socket(server_socket, cert_reqs=ssl.CERT_NONE, server_side=True, keyfile="server.key", certfile="server.crt").accept()

        status_messages.append(MESSAGE_INFO + "New client connected!")
        connections.append(client_connection) 
Example 26
Project: oscrypto   Author: wbond   File: _socket_proxy.py    MIT License 6 votes vote down vote up
def make_socket_proxy(ip, port, send_callback=None, recv_callback=None):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('', 8080))
    server.listen(1)
    t = threading.Thread(
        target=listen,
        args=(server, ip, port, send_callback, recv_callback)
    )
    t.start()
    sock = socket.create_connection(('localhost', 8080))
    sock.settimeout(1)
    t.join()
    with _socket_lock:
        data = _sockets[t.ident]
        return (sock, data['lsock'], data['rsock'], server) 
Example 27
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: socket.py    MIT License 6 votes vote down vote up
def _new_sock():
    sock = socket.socket(socket.AF_INET,
                         socket.SOCK_STREAM,
                         socket.IPPROTO_TCP)
    if platform.system() == 'Windows':
        try:
            sock.ioctl(socket.SIO_LOOPBACK_FAST_PATH, True)
        except AttributeError:
            pass  # Not supported in python 2.* or <3.6
        except OSError as ose:
            if ose.winerror == 10045:  # Not supported by OS
                pass
            else:
                raise
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
    else:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    return sock 
Example 28
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: socket.py    MIT License 6 votes vote down vote up
def apply(self, sock):
        """Set the keepalive values on the socket."""
        sock.setsockopt(socket.SOL_SOCKET,
                        socket.SO_KEEPALIVE,
                        1)
        interval = self.interval
        idle = self.idle
        maxfails = self.maxfails
        try:
            if interval > 0:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPINTVL,
                                interval)
            if idle > 0:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPIDLE,
                                idle)
            if maxfails >= 0:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPCNT,
                                maxfails)
        except AttributeError:
            # mostly linux-only
            pass 
Example 29
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: test_jyserver.py    MIT License 6 votes vote down vote up
def create_connections(self):
        '''
        Creates the connections needed for testing.
        '''
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((pycompletionserver.HOST, 0))
        server.listen(1)  #socket to receive messages.

        from thread import start_new_thread
        t = pycompletionserver.CompletionServer(server.getsockname()[1])
        t.exit_process_on_kill = False

        start_new_thread(t.run, ())

        sock, _addr = server.accept()

        return t, sock 
Example 30
Project: fs_image   Author: facebookincubator   File: send_fds_and_run.py    MIT License 5 votes vote down vote up
def send_fds(sock, fds):
    msg = b'unused'
    num_sent = sock.sendmsg([msg], [(
        socket.SOL_SOCKET, socket.SCM_RIGHTS,
        array.array('i', fds).tobytes(),
        # Future: is `flags=socket.MSG_NOSIGNAL` a good idea?
    )])
    assert len(msg) == num_sent, (msg, num_sent) 
Example 31
Project: fs_image   Author: facebookincubator   File: yum_dnf_from_snapshot.py    MIT License 5 votes vote down vote up
def _make_socket_and_send_via(*, unix_sock_fd):
    '''
    Creates a TCP stream socket and sends it elsewhere via the provided Unix
    domain socket file descriptor.  This is useful for obtaining a socket
    that belongs to a different network namespace (i.e.  creating a socket
    inside a container, but binding it from outside the container).

    IMPORTANT: This code must not write anything to stdout, the fd can be 1.
    '''
    # NB: Some code here is (sort of) copy-pasta'd in `send_fds_and_run.py`,
    # but it's not obviously worthwhile to reuse it here.
    return ['python3', '-c', textwrap.dedent('''\
    import array, socket, sys

    def send_fds(sock, msg: bytes, fds: 'List[int]'):
        num_sent = sock.sendmsg([msg], [(
            socket.SOL_SOCKET, socket.SCM_RIGHTS,
            array.array('i', fds).tobytes(),
            # Future: is `flags=socket.MSG_NOSIGNAL` a good idea?
        )])
        assert len(msg) == num_sent, (msg, num_sent)

    # Make a socket in this netns, and send it to the parent.
    with socket.socket(fileno=''' + str(unix_sock_fd) + ''') as lsock:
        print(f'Sending FD to parent', file=sys.stderr)
        lsock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
        with lsock.accept()[0] as csock, socket.socket(
            socket.AF_INET, socket.SOCK_STREAM
        ) as inet_sock:
            csock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
            send_fds(csock, b'ohai', [inet_sock.fileno()])
    ''')] 
Example 32
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def server_bind(self):
        """Called by constructor to bind the socket.

        May be overridden.

        """
        if self.allow_reuse_address:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)
        self.server_address = self.socket.getsockname() 
Example 33
Project: pyblish-win   Author: pyblish   File: asyncore.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def handle_connect_event(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            raise socket.error(err, _strerror(err))
        self.handle_connect()
        self.connected = True
        self.connecting = False 
Example 34
Project: pyblish-win   Author: pyblish   File: asyncore.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def handle_expt_event(self):
        # handle_expt_event() is called if there might be an error on the
        # socket, or if there is OOB data
        # check for the error condition first
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            # we can get here when select.select() says that there is an
            # exceptional condition on the socket
            # since there is an error, we'll go ahead and close the socket
            # like we would in a subclassed handle_read() that received no
            # data
            self.handle_close()
        else:
            self.handle_expt() 
Example 35
Project: pyblish-win   Author: pyblish   File: asyncore.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getsockopt(self, level, optname, buflen=None):
            if (level == socket.SOL_SOCKET and
                optname == socket.SO_ERROR and
                not buflen):
                return 0
            raise NotImplementedError("Only asyncore specific behaviour "
                                      "implemented.") 
Example 36
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testGetSockOpt(self):
        # Testing getsockopt()
        # We know a socket should start without reuse==0
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
        self.assertFalse(reuse != 0, "initial mode is reuse") 
Example 37
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSetSockOpt(self):
        # Testing setsockopt()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
        self.assertFalse(reuse == 0, "failed to set reuse mode") 
Example 38
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
        self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
                TIPC_LOWER, TIPC_UPPER)
        self.srv.bind(srvaddr)
        self.srv.listen(5)
        self.serverExplicitReady()
        self.conn, self.connaddr = self.srv.accept() 
Example 39
Project: pyblish-win   Author: pyblish   File: test_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def bind_port(sock, host=HOST):
    """Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.
    """
    if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
        if hasattr(socket, 'SO_REUSEADDR'):
            if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
                raise TestFailed("tests should never set the SO_REUSEADDR "   \
                                 "socket option on TCP/IP sockets!")
        if hasattr(socket, 'SO_REUSEPORT'):
            try:
                if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
                    raise TestFailed("tests should never set the SO_REUSEPORT "   \
                                     "socket option on TCP/IP sockets!")
            except EnvironmentError:
                # Python's socket module was compiled using modern headers
                # thus defining SO_REUSEPORT but this process is running
                # under an older kernel that does not support SO_REUSEPORT.
                pass
        if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)

    sock.bind((host, 0))
    port = sock.getsockname()[1]
    return port 
Example 40
Project: kuaa   Author: rafaelwerneck   File: socket_communication.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((config.COMMUNICATION_HOST, config.COMMUNICATION_PORT))
        s.listen(0)

        remaining_data = ""

        while True:
            conn, addr = s.accept()

            while True:
                data = conn.recv(1024)

                if not data:
                    break

                msgs = remaining_data + data
                msgs = data.split(config.MESSAGE_SEPARATOR)
                remaining_data = msgs.pop()

                for msg in msgs:
                    if msg is None:
                        continue

                    index = msg.find(' ')
                    msg_id = msg[:index]
                    msg = msg[index + 1:]

                    for item in self._callbacks:
                        if item[0] is None or msg_id in item[0]:
                            item[1](msg_id, msg)

            conn.close() 
Example 41
Project: programsynthesishunting   Author: flexgp   File: TCPScanner.py    GNU General Public License v3.0 5 votes vote down vote up
def TCP_connect(self, ip, port_number, retries):
        TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        TCPsock.settimeout(self.timeout)
        count = 0
        while count <= retries:
            try:
                TCPsock.connect((ip, port_number))
                self.scan_dic[ip + ":" + str(port_number)] = 'Listening'
                break
            except:
                self.scan_dic[ip + ":" + str(port_number)] = 'No Response'
                count += 1 
Example 42
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: wakeonlan.py    MIT License 5 votes vote down vote up
def wakeonlan(module, mac, broadcast, port):
    """ Send a magic Wake-on-LAN packet. """

    mac_orig = mac

    # Remove possible separator from MAC address
    if len(mac) == 12 + 5:
        mac = mac.replace(mac[2], '')

    # If we don't end up with 12 hexadecimal characters, fail
    if len(mac) != 12:
        module.fail_json(msg="Incorrect MAC address length: %s" % mac_orig)

    # Test if it converts to an integer, otherwise fail
    try:
        int(mac, 16)
    except ValueError:
        module.fail_json(msg="Incorrect MAC address format: %s" % mac_orig)

    # Create payload for magic packet
    data = b''
    padding = ''.join(['FFFFFFFFFFFF', mac * 20])
    for i in range(0, len(padding), 2):
        data = b''.join([data, struct.pack('B', int(padding[i: i + 2], 16))])

    # Broadcast payload to network
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    if not module.check_mode:

        try:
            sock.sendto(data, (broadcast, port))
        except socket.error as e:
            sock.close()
            module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    sock.close() 
Example 43
Project: ps4-remote-play   Author: kingcreek   File: discovery.py    Apache License 2.0 5 votes vote down vote up
def find_console(console, timeout=3.0):
    """Finds a console on the local network and returns its status."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.bind(('', 12345))

    data = b'SRCH * HTTP/1.1\r\n'
    data += b'device - discovery - protocol - version:0020020\r\n'
    data += b'\r\n'

    deadline = time.time() + timeout
    while time.time() < deadline:
        sock.sendto(data, ('255.255.255.255', _DISCOVERY_PORT))
        sock.settimeout(deadline - time.time())
        try:
            data, addr = sock.recvfrom(65536)
        except socket.timeout:
            break

        code, headers = _parse_http_response(data)
        if binascii.a2b_hex(headers['host-id']) != console.host_id:
            continue
        if code == 620:
            status = ConsoleStatus.standby
        else:
            status = ConsoleStatus.ready
        return addr[0], status

    return None, None 
Example 44
Project: ps4-remote-play   Author: kingcreek   File: registration.py    Apache License 2.0 5 votes vote down vote up
def _find_console():
    bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    bsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    bsock.bind(('', _RP_CONTROL_PORT))

    bsock.sendto(b'SRC2', ('255.255.255.255', _RP_CONTROL_PORT))
    bsock.settimeout(2.0)
    try:
        while True:
            data, (ip, port) = bsock.recvfrom(65536)
            if data[:4] == b'RES2' and port == _RP_CONTROL_PORT:
                return ip
    except socket.timeout:
        return None 
Example 45
Project: flasky   Author: RoseOu   File: sock.py    MIT License 5 votes vote down vote up
def set_options(self, sock, bound=False):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if not bound:
            self.bind(sock)
        sock.setblocking(0)

        # make sure that the socket can be inherited
        if hasattr(sock, "set_inheritable"):
            sock.set_inheritable(True)

        sock.listen(self.conf.backlog)
        return sock 
Example 46
Project: radius-1xtest   Author: shanghai-edu   File: client.py    Apache License 2.0 5 votes vote down vote up
def _SocketOpen(self):
        if not self._socket:
            self._socket=socket.socket(socket.AF_INET,
                                       socket.SOCK_DGRAM)
            self._socket.setsockopt(socket.SOL_SOCKET,
                                    socket.SO_REUSEADDR, 1) 
Example 47
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    MIT License 5 votes vote down vote up
def serve(self):
		client_socket = server_socket = None
		self.threads = []
		threadsnum = 0

		common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
		server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			server_socket.bind((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
			while not self._stop:
				server_socket.listen(1) #?? 1 ??
				client_socket, client_addr = server_socket.accept()
				common.internal_print(("Client connected: {0}".format(client_addr)), 0, self.verbosity, common.DEBUG)

				threadsnum = threadsnum + 1
				thread = TCP_generic_thread(threadsnum, 1, self.tunnel, self.packetselector, client_socket, client_addr, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
				thread.start()
				self.threads.append(thread)
			if self._stop:
				self.stop()

		except socket.error as exception:
			# [Errno 98] Address already in use
			if ((self.os_type == common.OS_LINUX) and (exception.args[0] == 98)) or ((self.os_type == common.OS_MACOSX) and (exception.args[0] == 48)):
				common.internal_print("Starting failed, port is in use: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))), -1)
			else:
				raise

		self.cleanup(server_socket)

		return 
Example 48
Project: XFLTReaT   Author: earthquake   File: DNS.py    MIT License 5 votes vote down vote up
def serve(self):
		server_socket = None
		if self.zonefile:
			(hostname, self.ttl, self.zone) = self.DNS_common.parse_zone_file(self.zonefile)
			if hostname and (hostname+"." != self.hostname):
				common.internal_print("'hostname' in '{0}' section does not match with the zonefile's origin".format(self.get_module_configname()), -1)
				return
		try:
			common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), self.serverport))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			whereto = (self.config.get("Global", "serverbind"), self.serverport)
			server_socket.bind(whereto)
			self.comms_socket = server_socket
			self.serverorclient = 1
			self.authenticated = False

			self.communication_initialization()
			self.communication(False) 
			
		except KeyboardInterrupt:

			self.cleanup()
			return

		self.cleanup()

		return 
Example 49
Project: XFLTReaT   Author: earthquake   File: SCTP_generic.py    MIT License 5 votes vote down vote up
def serve(self):
		client_socket = server_socket = None
		self.threads = []
		threadsnum = 0

		common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
		server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			server_socket.bind((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
			while not self._stop:
				server_socket.listen(1) #?? 1 ??
				client_socket, client_addr = server_socket.accept()
				common.internal_print(("Client connected: {0}".format(client_addr)), 0, self.verbosity, common.DEBUG)

				threadsnum = threadsnum + 1
				thread = SCTP_generic_thread(threadsnum, 1, self.tunnel, self.packetselector, client_socket, client_addr, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
				thread.start()
				self.threads.append(thread)
			if self._stop:
				self.stop()

		except socket.error as exception:
			# [Errno 98] Address already in use
			if exception.args[0] != 98:
				raise
			else:
				common.internal_print("Starting failed, port is in use: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))), -1)

		self.cleanup(server_socket)

		return 
Example 50
Project: XFLTReaT   Author: earthquake   File: WebSocket.py    MIT License 5 votes vote down vote up
def serve(self):
		client_socket = server_socket = None
		self.threads = []
		threadsnum = 0

		common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
		server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

		try:
			server_socket.bind((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
			while not self._stop:
				server_socket.listen(1) #?? 1 ??
				client_socket, client_addr = server_socket.accept()
				common.internal_print(("Client connected: {0}".format(client_addr)), 0, self.verbosity, common.DEBUG)

				threadsnum = threadsnum + 1
				thread = WebSocket_thread(threadsnum, 1, self.tunnel, self.packetselector, client_socket, client_addr, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
				thread.start()
				self.threads.append(thread)

		except socket.error as exception:
			# [Errno 98] Address already in use
			if exception.args[0] != 98:
				raise
			else:
				common.internal_print("Starting failed, port is in use: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))), -1)

		self.cleanup(server_socket)

		return