Python socket.SO_REUSEADDR Examples

The following are 30 code examples of socket.SO_REUSEADDR(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: server.py    From RF-Monitor with GNU General Public License v2.0 10 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 #2
Source File: multicast_checks.py    From rift-python with Apache License 2.0 7 votes vote down vote up
def _create_ipv4_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    mcast_address = "224.0.1.195"
    port = 49501
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=4sl", socket.inet_aton(mcast_address), socket.INADDR_ANY)
    rxsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
    rxsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    rxsock.bind(group)
    return (txsock, rxsock) 
Example #3
Source File: script_runner.py    From InsightAgent with Apache License 2.0 7 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 #4
Source File: multicast-relay.py    From multicast-relay with GNU General Public License v3.0 6 votes vote down vote up
def addListener(self, addr, port, service):
        if self.isBroadcast(addr):
            self.etherAddrs[addr] = self.broadcastIpToMac(addr)
        elif self.isMulticast(addr):
            self.etherAddrs[addr] = self.multicastIpToMac(addr)
        else:
            # unicast -- we don't know yet which IP we'll want to send to
            self.etherAddrs[addr] = None

        # Set up the receiving socket and corresponding IP and interface information.
        # One receiving socket is required per multicast address.
        rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
        rx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        for interface in self.interfaces:
            (ifname, mac, ip, netmask) = self.getInterface(interface)

            # Add this interface to the receiving socket's list.
            if self.isBroadcast(addr):
                rx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            elif self.isMulticast(addr):
                packedAddress = struct.pack('4s4s', socket.inet_aton(addr), socket.inet_aton(ip))
                rx.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, packedAddress)

            # Generate a transmitter socket. Each interface
            # requires its own transmitting socket.
            if interface not in self.noTransmitInterfaces:
                tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
                tx.bind((ifname, 0))

                self.transmitters.append({'relay': {'addr': addr, 'port': port}, 'interface': ifname, 'addr': ip, 'mac': mac, 'netmask': netmask, 'socket': tx, 'service': service})

        rx.bind((addr, port))
        self.receivers.append(rx) 
Example #5
Source File: UDP_generic.py    From XFLTReaT with 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 #6
Source File: _socket_proxy.py    From oscrypto with 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 #7
Source File: reporting_send.py    From InsightAgent with 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 #8
Source File: matlab_gui_controller.py    From vim-matlab with Mozilla Public License 2.0 6 votes vote down vote up
def __launch_key_request_process(self):
        """
        Pick an unused port and start a TCP server. MATLAB will send callback
        requests through this socket.
        :return: port
        """
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(('localhost', 0))
        _, self.key_handler_port = self.sock.getsockname()

        self.key_handler_queue = multiprocessing.Queue()
        self.key_handler = multiprocessing.Process(
            target=self.__key_request_handler,
            args=(self.sock,
                  [self.command_window_id,
                   self.editor_window_id,
                   self.vim_window_id],
                  self.key_handler_queue)
        )
        self.key_handler.start()
        self.key_handler_queue.get(True, 5)
        return self.key_handler_port 
Example #9
Source File: proxy.py    From RAT-via-Telegram with MIT License 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 #10
Source File: server.py    From sanic with MIT License 6 votes vote down vote up
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
    """Create TCP server socket.
    :param host: IPv4, IPv6 or hostname may be specified
    :param port: TCP port number
    :param backlog: Maximum number of connections to queue
    :return: socket.socket object
    """
    try:  # IP address: family must be specified for IPv6 at least
        ip = ip_address(host)
        host = str(ip)
        sock = socket.socket(
            socket.AF_INET6 if ip.version == 6 else socket.AF_INET
        )
    except ValueError:  # Hostname, may become AF_INET or AF_INET6
        sock = socket.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(backlog)
    return sock 
Example #11
Source File: mavlink.py    From dronekit-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, device, baud=None, input=True, broadcast=False, source_system=255, source_component=0, use_native=mavutil.default_native):
        self._logger = logging.getLogger(__name__)
        a = device.split(':')
        if len(a) != 2:
            self._logger.critical("UDP ports must be specified as host:port")
            sys.exit(1)
        self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_server = input
        self.broadcast = False
        self.addresses = set()
        if input:
            self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.port.bind((a[0], int(a[1])))
        else:
            self.destination_addr = (a[0], int(a[1]))
            if broadcast:
                self.port.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
                self.broadcast = True
        mavutil.set_close_on_exec(self.port.fileno())
        self.port.setblocking(False)
        mavutil.mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, source_component=source_component, input=input, use_native=use_native) 
Example #12
Source File: XAsyncSockets.py    From MicroWebSrv2 with MIT License 6 votes vote down vote up
def Create(asyncSocketsPool, srvAddr, srvBacklog=256, bufSlots=None) :
        try :
            srvSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except :
            raise XAsyncTCPServerException('Create : Cannot open socket (no enought memory).')
        try :
            srvSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            srvSocket.bind(srvAddr)
            srvSocket.listen(srvBacklog)
        except :
            raise XAsyncTCPServerException('Create : Error to binding the TCP server on this address.')
        if not bufSlots :
            bufSlots = XBufferSlots(256, 4096, keepAlloc=True)
        xAsyncTCPServer = XAsyncTCPServer( asyncSocketsPool,
                                           srvSocket,
                                           srvAddr,
                                           bufSlots )
        asyncSocketsPool.NotifyNextReadyForReading(xAsyncTCPServer, True)
        return xAsyncTCPServer

    # ------------------------------------------------------------------------ 
Example #13
Source File: test_timeout.py    From dronekit-python with Apache License 2.0 6 votes vote down vote up
def test_timeout_empty():
    # Create a dummy server.
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('127.0.0.1', 5760))
    s.listen(1)

    try:
        # Connect with timeout of 10s.
        vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True, heartbeat_timeout=20)

        vehicle.close()

        # Should not pass
        assert False
    except:
        pass 
Example #14
Source File: Server.py    From EvilOSX with 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 #15
Source File: http.py    From ftw with Apache License 2.0 6 votes vote down vote up
def build_socket(self):
        """
        Generate either an HTTPS or HTTP socket
        """
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(self.SOCKET_TIMEOUT)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # Check if TLS
            if self.request_object.protocol == 'https':
                self.sock = ssl.wrap_socket(self.sock, ciphers=self.CIPHERS)
            self.sock.connect(
                (self.request_object.dest_addr, self.request_object.port))
        except socket.error as msg:
            raise errors.TestError(
                'Failed to connect to server',
                {
                    'host': self.request_object.dest_addr,
                    'port': self.request_object.port,
                    'proto': self.request_object.protocol,
                    'message': msg,
                    'function': 'http.HttpUA.build_socket'
                }) 
Example #16
Source File: multicast_checks.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def _create_ipv6_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    intf_name = find_ethernet_interface()
    intf_index = socket.if_nametoindex(intf_name)
    mcast_address = "ff02::abcd:99"
    port = 30000
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, intf_index)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=16si", socket.inet_pton(socket.AF_INET6, mcast_address), intf_index)
    if platform.system() == "Darwin":
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, req)
    else:
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_ADD_MEMBERSHIP, req)
    rxsock.bind(("::", port))
    return (txsock, rxsock) 
Example #17
Source File: tcpserverpiped.py    From moler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prepare_server_socket(self):
        """Create, configure and start server-listening socket"""
        self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        svr_addr = (self.host, self.port)
        self.server_sock.bind(svr_addr)
        self.server_sock.setblocking(1)
        self.server_sock.listen(1)
        self.logger.debug("listening on %s:%s" % svr_addr) 
Example #18
Source File: listen.py    From insightconnect-plugins with MIT License 5 votes vote down vote up
def run():
    """Run the trigger"""
    # send a test event

    BUFF = 4096
    interval = 10
    protocol = 'http'
    endpoint = '0.0.0.0'
    tcp_port = 8080

    host = protocol + "://" + endpoint + ":" + str(tcp_port)
    print('Listening on', host)

    # Open socket server to listen for messages
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((endpoint, tcp_port))
    server.listen(5)

    while True:
      conn, addr = server.accept()
      print(conn, addr)
      recv_data = conn.recv(BUFF)
      print(recv_data)
      conn.sendall(recv_data)
      conn.close()

      # Handler receiving data
      handler_data(recv_data.decode('utf-8'))
      time.sleep(interval) 
Example #19
Source File: sftpd.py    From geofront with GNU Affero General Public License v3.0 5 votes vote down vote up
def start_server(path: str, host: str, port: int, terminated: threading.Event):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.settimeout(1)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    server_socket.bind((host, port))
    server_socket.listen(1)
    stub_cls = type('StubSFTPServer', (StubSFTPServer,), {'ROOT': path})
    host_key = RSAKey.generate(1024)

    def accept(server_socket, mask):
        conn, addr = server_socket.accept()
        transport = Transport(conn)
        transport.add_server_key(host_key)
        transport.set_subsystem_handler('sftp', SFTPServer, stub_cls)
        server = StubServer(path)
        transport.start_server(server=server)
        while not terminated.is_set():
            channel = transport.accept(1)
            if channel is not None and not terminated.is_set():
                while transport.is_active() and not terminated.is_set():
                    terminated.wait(1)
                break

    sel = selectors.DefaultSelector()
    sel.register(server_socket, selectors.EVENT_READ, accept)
    last_used = time.time()
    while not terminated.is_set() and last_used + 10 > time.time():
        events = sel.select(1)
        for key, mask in events:
            key.data(key.fileobj, mask)
            last_used = time.time() 
Example #20
Source File: discover.py    From pulseaudio-dlna with GNU General Public License v3.0 5 votes vote down vote up
def _search(self, host, ssdp_ttl, ssdp_mx, ssdp_amount):
        logger.debug('Binding socket to "{}" ...'.format(host or ''))
        sock = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.settimeout(ssdp_mx)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_MULTICAST_TTL,
            ssdp_ttl)
        sock.bind((host, self.MSEARCH_PORT))

        for i in range(1, ssdp_amount + 1):
            t = threading.Timer(
                float(i) / 2, self._send_discover, args=[sock, ssdp_mx])
            t.start()

        while True:
            try:
                header, address = sock.recvfrom(self.BUFFER_SIZE)
                if self.cb_on_device_response:
                    guess = chardet.detect(header)
                    header = header.decode(guess['encoding'])
                    header = pulseaudio_dlna.plugins.dlna.ssdp._get_header_map(
                        header)
                    self.cb_on_device_response(header, address)
            except socket.timeout:
                break
        sock.close() 
Example #21
Source File: socketserverhandler.py    From Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader with MIT License 5 votes vote down vote up
def startServer():
    database.beginDataBaseConnection()
    database.initDatabase()
    server_address = (settings.server_location, int(settings.server_port))
    print('Starting server on %s port %s' % server_address)
    socket.setsockopt(pythonsocket.SOL_SOCKET, pythonsocket.SO_REUSEADDR, 1)
    socket.settimeout(None)
    socket.bind(server_address)
    socket.listen(5)
    socket.settimeout(None)
    thread = Thread(target=waitConnect)
    thread.start()
    servertick = Thread(target=serverTick)
    servertick.start() 
Example #22
Source File: rangefetch_server.py    From bilibiliupload with MIT License 5 votes vote down vote up
def server_bind(self):
        sock = self.socket
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
        self.RequestHandlerClass.bufsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        SocketServer.TCPServer.server_bind(self) 
Example #23
Source File: udp.py    From BiblioPixel with MIT License 5 votes vote down vote up
def __init__(self, address, bufsize=0x1000, receive=None, **kwds):
        super().__init__(**kwds)
        self.address = address
        self.bufsize = bufsize
        self.receive = receive or self.receive
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.address) 
Example #24
Source File: threaded_ping_server.py    From moler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start_ping_sim_server(server_address, ping_ip):
    """Run server simulating ping command output, this is one-shot server"""
    _, server_port = server_address
    logger = logging.getLogger('threaded.ping.tcp-server({})'.format(server_port))
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(server_address)
    server_socket.listen(1)
    logger.debug("Ping Sim started at tcp://{}:{}".format(*server_address))
    done_event = threading.Event()
    server_thread = threading.Thread(target=server_loop,
                                     args=(server_port, server_socket, ping_ip,
                                           done_event))
    server_thread.start()
    return server_thread, done_event 
Example #25
Source File: connection_manager.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def _server_discovery(self):
        
        MULTI_GROUP = ("<broadcast>", 7359)
        MESSAGE = "who is EmbyServer?"
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(1.0) # This controls the socket.timeout exception
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.SO_REUSEADDR, 1)
        
        LOG.debug("MultiGroup      : %s", str(MULTI_GROUP))
        LOG.debug("Sending UDP Data: %s", MESSAGE)
        servers = []

        try:
            sock.sendto(MESSAGE, MULTI_GROUP)
        except Exception as error:
            LOG.error(error)

            return servers

        while True:
            try:
                data, addr = sock.recvfrom(1024) # buffer size
                servers.append(json.loads(data))
            
            except socket.timeout:
                LOG.info("Found Servers: %s", servers)

                return servers
            
            except Exception as e:
                LOG.error("Error trying to find servers: %s", e)

                return servers 
Example #26
Source File: test_utils.py    From sagemaker-xgboost-container with Apache License 2.0 5 votes vote down vote up
def find_two_open_ports():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s1:
        s1.bind(('', 0))
        s1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s2:
            s2.bind(('', 0))
            s2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

            return s1.getsockname()[1], s2.getsockname()[1] 
Example #27
Source File: www.py    From stream with MIT License 5 votes vote down vote up
def main():
  server = gsocket(socket.AF_INET, socket.SOCK_STREAM)
  server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  server.bind(("0.0.0.0", 8080))  
  server.listen(5)

  while True:
    conn, addr = server.accept()
    print "[  INFO  ] New connection: %s:%i" % addr

    th = Handler(conn, addr)
    th.daemon = False
    th.start() 
Example #28
Source File: proxyhttp.py    From stream with MIT License 5 votes vote down vote up
def main():
  while True:

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
      s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
      s.bind((HOST, PORT))
      s.listen(16)
      conn, addr = s.accept()

      try:
        p = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        p.connect((DST_HOST, DST_PORT))
      except ConnectionError:
        print("Failed to connect to wordpress")
        conn.shutdown(socket.SHUT_RDWR)
        continue

      p.settimeout(1)
      conn.settimeout(1)

      end = threading.Event()

      rth = threading.Thread(target=recv_thread, args=(conn, p, end), daemon=True)
      sth = threading.Thread(target=send_thread, args=(conn, p, end, rth), daemon=True)

      rth.start()
      sth.start() 
Example #29
Source File: server.py    From stream with MIT License 5 votes vote down vote up
def handle(self):
    self.request.sendall(b"220 Livestream FTP Server.\r\n")
    self.request.settimeout(60)

    self.end_connection = False
    self.data_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.data_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.data_s.bind(("0.0.0.0", 0))
    self.data_s.listen(1)
    self.data_port = self.data_s.getsockname()[1]

    self.cwd = []
    methods = {}
    self.files = {
      "<h1>asdgf<u>xyz": b"<h1>asdfg<u>asdgf<script>alert(document.domain)</script>",
      "asdg\\..\\xyz": b"\0\1\2\3\4\xff" * 1234,
      "dir": {
        "abc": b"abc"
      }
    }

    for method_name in dir(self):
      if method_name.startswith("handle_"):
        cmd = method_name.replace("handle_", "")
        methods[cmd] = getattr(self, method_name)

    while not self.end_connection:
      ln = str(recvuntil(self.request, b"\r\n", 4096), 'utf-8').strip()
      print(ln)
      command, args = (ln.split(" ", 1) + [""])[:2]
      if command in methods:
        methods[command](args)
        continue
      else:
        print("---> command unknown: %s" % command)



      break 
Example #30
Source File: server.py    From stream with MIT License 5 votes vote down vote up
def handle(self):
    self.request.sendall(b"220 Livestream FTP Server.\r\n")
    self.request.settimeout(60)

    self.end_connection = False
    self.data_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.data_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.data_s.bind(("0.0.0.0", 0))
    self.data_s.listen(1)
    self.data_port = self.data_s.getsockname()[1]

    self.cwd = []
    methods = {}
    self.files = {
      "<h1>asdgf<u>xyz": b"<h1>asdfg<u>asdgf",
      "dir": {
        "abc": b"abc"
      }
    }

    for method_name in dir(self):
      if method_name.startswith("handle_"):
        cmd = method_name.replace("handle_", "")
        methods[cmd] = getattr(self, method_name)

    while not self.end_connection:
      ln = str(recvuntil(self.request, b"\r\n", 4096), 'utf-8').strip()
      print(ln)
      command, args = (ln.split(" ", 1) + [""])[:2]
      if command in methods:
        methods[command](args)
        continue

      break