Python errno 模块,EADDRINUSE 实例源码

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

项目:dappled    作者:lhon    | 项目源码 | 文件源码
def get_free_port(port, port_retries):
    for port in random_ports(port, port_retries+1):
        try:
            s = socket.socket()
            s.bind(('', port))
            port = s.getsockname()[1]
            s.close()
            return port
        except socket.error as e:
            if e.errno == errno.EADDRINUSE:
                print('The port %i is already in use, trying another port.' % port)
                continue
            elif e.errno in (errno.EACCES, getattr(errno, 'WSAEACCES', errno.EACCES)):
                print("Permission to listen on port %i denied" % port)
                continue
            else:
                raise
    return None

# http://stackoverflow.com/questions/13593223/making-sure-a-python-script-with-subprocesses-dies-on-sigint
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_create_server_addr_in_use(self):
        sock_ob = socket.socket(type=socket.SOCK_STREAM)
        sock_ob.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock_ob.bind(('0.0.0.0', 0))

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

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

        server.close()
项目:nfcpy    作者:nfcpy    | 项目源码 | 文件源码
def test_bind_by_addr(self, llc, raw, ldl, dlc):
            llc.bind(raw, 16)
            assert llc.getsockname(raw) == 16
            for i, sock in enumerate([ldl, dlc]):
                with pytest.raises(nfc.llcp.Error) as excinfo:
                    llc.bind(sock, 16)
                assert excinfo.value.errno == errno.EACCES
            llc.bind(ldl, 63)
            assert llc.getsockname(ldl) == 63
            with pytest.raises(nfc.llcp.Error) as excinfo:
                llc.bind(dlc, 63)
            assert excinfo.value.errno == errno.EADDRINUSE
            with pytest.raises(nfc.llcp.Error) as excinfo:
                llc.bind(dlc, 64)
            assert excinfo.value.errno == errno.EFAULT
            with pytest.raises(nfc.llcp.Error) as excinfo:
                llc.bind(dlc, -1)
            assert excinfo.value.errno == errno.EFAULT
            llc.bind(dlc, 62)
            assert llc.getsockname(dlc) == 62
项目:nfcpy    作者:nfcpy    | 项目源码 | 文件源码
def test_bind_by_name(self, llc, raw, ldl, dlc):
            with pytest.raises(nfc.llcp.Error) as excinfo:
                llc.bind(dlc, 'urn:nfc:snep')
            assert excinfo.value.errno == errno.EFAULT
            llc.bind(dlc, 'urn:nfc:sn:snep')
            assert llc.getsockname(dlc) == 4
            with pytest.raises(nfc.llcp.Error) as excinfo:
                llc.bind(ldl, 'urn:nfc:sn:snep')
            assert excinfo.value.errno == errno.EADDRINUSE
            llc.bind(ldl, 'urn:nfc:xsn:nfcpy.org:service')
            assert llc.getsockname(ldl) == 16
            for sap in range(17, 32):
                sock = llc.socket(nfc.llcp.llc.RAW_ACCESS_POINT)
                llc.bind(sock, 'urn:nfc:sn:use_sap-{}'.format(sap))
                assert llc.getsockname(sock) == sap
            with pytest.raises(nfc.llcp.Error) as excinfo:
                llc.bind(raw, 'urn:nfc:sn:sap-32')
            assert excinfo.value.errno == errno.EADDRNOTAVAIL
项目:nfcpy    作者:nfcpy    | 项目源码 | 文件源码
def _bind_by_name(self, socket, name):
        if not service_name_format.match(name):
            raise err.Error(errno.EFAULT)

        with self.lock:
            if self.snl.get(name) is not None:
                raise err.Error(errno.EADDRINUSE)
            addr = wks_map.get(name)
            if addr is None:
                try:
                    addr = 16 + self.sap[16:32].index(None)
                except ValueError:
                    raise err.Error(errno.EADDRNOTAVAIL)
            socket.bind(addr)
            self.sap[addr] = ServiceAccessPoint(addr, self)
            self.sap[addr].insert_socket(socket)
            self.snl[name] = addr
项目:networkzero    作者:tjguk    | 项目源码 | 文件源码
def _bind_with_timeout(bind_function, args, n_tries=3, retry_interval_s=0.5):
    """Attempt to bind a socket a number of times with a short interval in between

    Especially on Linux, crashing out of a networkzero process can leave the sockets
    lingering and unable to re-bind on startup. We give it a few goes here to see if
    we can bind within a couple of seconds.
    """
    n_tries_left = n_tries
    while n_tries_left > 0:
        try:
            return bind_function(*args)
        except zmq.error.ZMQError as exc:
            _logger.warn("%s; %d tries remaining", exc, n_tries_left)
            n_tries_left -= 1
        except OSError as exc:
            if exc.errno == errno.EADDRINUSE:
                _logger.warn("%s; %d tries remaining", exc, n_tries_left)
                n_tries_left -= 1
            else:
                raise
    else:
        raise core.SocketAlreadyExistsError("Failed to bind after %s tries" % n_tries)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_getsockaddrarg(self):
        sock = socket.socket()
        self.addCleanup(sock.close)
        port = test_support.find_unused_port()
        big_port = port + 65536
        neg_port = port - 65536
        self.assertRaises(OverflowError, sock.bind, (HOST, big_port))
        self.assertRaises(OverflowError, sock.bind, (HOST, neg_port))
        # Since find_unused_port() is inherently subject to race conditions, we
        # call it a couple times if necessary.
        for i in itertools.count():
            port = test_support.find_unused_port()
            try:
                sock.bind((HOST, port))
            except OSError as e:
                if e.errno != errno.EADDRINUSE or i == 5:
                    raise
            else:
                break
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_getsockaddrarg(self):
        sock = socket.socket()
        self.addCleanup(sock.close)
        port = test_support.find_unused_port()
        big_port = port + 65536
        neg_port = port - 65536
        self.assertRaises(OverflowError, sock.bind, (HOST, big_port))
        self.assertRaises(OverflowError, sock.bind, (HOST, neg_port))
        # Since find_unused_port() is inherently subject to race conditions, we
        # call it a couple times if necessary.
        for i in itertools.count():
            port = test_support.find_unused_port()
            try:
                sock.bind((HOST, port))
            except OSError as e:
                if e.errno != errno.EADDRINUSE or i == 5:
                    raise
            else:
                break
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def test__allocate_sockets(self):
        """Test allocating sockets.
        """
        # access protected module _allocate_sockets
        # pylint: disable=w0212

        socket.socket.bind.side_effect = [
            socket.error(errno.EADDRINUSE, 'In use'),
            mock.DEFAULT,
            mock.DEFAULT,
            mock.DEFAULT
        ]

        sockets = treadmill.runtime._allocate_sockets(
            'prod', '0.0.0.0', socket.SOCK_STREAM, 3
        )

        self.assertEqual(3, len(sockets))
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_getsockaddrarg(self):
        sock = socket.socket()
        self.addCleanup(sock.close)
        port = test_support.find_unused_port()
        big_port = port + 65536
        neg_port = port - 65536
        self.assertRaises((OverflowError, ValueError), sock.bind, (HOST, big_port))
        self.assertRaises((OverflowError, ValueError), sock.bind, (HOST, neg_port))
        # Since find_unused_port() is inherently subject to race conditions, we
        # call it a couple times if necessary.
        for i in itertools.count():
            port = test_support.find_unused_port()
            try:
                sock.bind((HOST, port))
            except OSError as e:
                if e.errno != errno.EADDRINUSE or i == 5:
                    raise
            else:
                break
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_getsockaddrarg(self):
        sock = socket.socket()
        self.addCleanup(sock.close)
        port = support.find_unused_port()
        big_port = port + 65536
        neg_port = port - 65536
        self.assertRaises(OverflowError, sock.bind, (HOST, big_port))
        self.assertRaises(OverflowError, sock.bind, (HOST, neg_port))
        # Since find_unused_port() is inherently subject to race conditions, we
        # call it a couple times if necessary.
        for i in itertools.count():
            port = support.find_unused_port()
            try:
                sock.bind((HOST, port))
            except OSError as e:
                if e.errno != errno.EADDRINUSE or i == 5:
                    raise
            else:
                break
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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()
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def test_retry_limited(self):
    inet4_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
                     for _ in range(wsgi_server._PORT_0_RETRIES)]
    inet6_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
                     for _ in range(wsgi_server._PORT_0_RETRIES)]
    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                       socket.AI_PASSIVE).AndReturn(
                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
                            (None, None, None, None, ('::1', 0, 'baz'))])
    for offset, (inet4_server, inet6_server) in enumerate(zip(
        inet4_servers, inet6_servers)):
      wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
          inet4_server)
      inet4_server.start()
      inet4_server.port = offset + 1
      wsgi_server._SingleAddressWsgiServer(('::1', offset + 1), None).AndReturn(
          inet6_server)
      inet6_server.start().AndRaise(
          wsgi_server.BindError('message', (errno.EADDRINUSE, 'in use')))
      inet4_server.quit()
    self.mox.ReplayAll()
    self.assertRaises(wsgi_server.BindError, self.server.start)
    self.mox.VerifyAll()
项目:asyncpg    作者:MagicStack    | 项目源码 | 文件源码
def find_available_port(port_range=(49152, 65535), max_tries=1000):
    low, high = port_range

    port = low
    try_no = 0

    while try_no < max_tries:
        try_no += 1
        port = random.randint(low, high)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind(('127.0.0.1', port))
        except socket.error as e:
            if e.errno == errno.EADDRINUSE:
                continue
        finally:
            sock.close()

        break
    else:
        port = None

    return port
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_getsockaddrarg(self):
        sock = socket.socket()
        self.addCleanup(sock.close)
        port = support.find_unused_port()
        big_port = port + 65536
        neg_port = port - 65536
        self.assertRaises(OverflowError, sock.bind, (HOST, big_port))
        self.assertRaises(OverflowError, sock.bind, (HOST, neg_port))
        # Since find_unused_port() is inherently subject to race conditions, we
        # call it a couple times if necessary.
        for i in itertools.count():
            port = support.find_unused_port()
            try:
                sock.bind((HOST, port))
            except OSError as e:
                if e.errno != errno.EADDRINUSE or i == 5:
                    raise
            else:
                break
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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()
项目:pykit    作者:baishancloud    | 项目源码 | 文件源码
def _lock(self):

        if OS == 'Linux':
            so = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            try:
                addr = '\0/portlock/' + self.key
                so.bind(addr)
                self.socks[0] = so
                logger.debug('success to bind: {addr}'.format(addr=addr))
            except socket.error as e:
                if e.errno == errno.EADDRINUSE:
                    logger.debug('failure to bind: {addr}'.format(addr=addr))
                else:
                    raise

            return

        # other OS

        for i in range(len(self.socks)):

            addr = (self.addr[0], self.addr[1] + i)

            so = self._socket()

            try:
                so.bind(addr)
                self.socks[i] = so
                logger.debug('success to bind: {addr}'.format(addr=addr))
            except socket.error as e:
                if e.errno == errno.EADDRINUSE:
                    logger.debug('failure to bind: {addr}'.format(addr=addr))
                else:
                    raise
项目:iotronic    作者:openstack    | 项目源码 | 文件源码
def _listen(host, start_port, end_port, listen_func):
    try_port = start_port
    while True:
        try:
            return listen_func((host, try_port))
        except socket.error as exc:
            if (exc.errno != errno.EADDRINUSE or
                    try_port >= end_port):
                raise
            try_port += 1
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def run(self):
        """
        Sets up the live server and databases, and then loops over handling
        http requests.
        """
        if self.connections_override:
            # Override this thread's database connections with the ones
            # provided by the main thread.
            for alias, conn in self.connections_override.items():
                connections[alias] = conn
        try:
            # Create the handler for serving static and media files
            handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))

            # Go through the list of possible ports, hoping that we can find
            # one that is free to use for the WSGI server.
            for index, port in enumerate(self.possible_ports):
                try:
                    self.httpd = self._create_server(port)
                except socket.error as e:
                    if (index + 1 < len(self.possible_ports) and
                            e.errno == errno.EADDRINUSE):
                        # This port is already in use, so we go on and try with
                        # the next one in the list.
                        continue
                    else:
                        # Either none of the given ports are free or the error
                        # is something else than "Address already in use". So
                        # we let that error bubble up to the main thread.
                        raise
                else:
                    # A free port was found.
                    self.port = port
                    break

            self.httpd.set_app(handler)
            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_create_connection_local_addr_in_use(self):
        with test_utils.run_test_server() as httpd:
            f = self.loop.create_connection(
                lambda: MyProto(loop=self.loop),
                *httpd.address, local_addr=httpd.address)
            with self.assertRaises(OSError) as cm:
                self.loop.run_until_complete(f)
            self.assertEqual(cm.exception.errno, errno.EADDRINUSE)
            self.assertIn(str(httpd.address), cm.exception.strerror)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_create_server_dual_stack(self):
        f_proto = asyncio.Future(loop=self.loop)

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

        try_count = 0
        while True:
            try:
                port = support.find_unused_port()
                f = self.loop.create_server(TestMyProto, host=None, port=port)
                server = self.loop.run_until_complete(f)
            except OSError as ex:
                if ex.errno == errno.EADDRINUSE:
                    try_count += 1
                    self.assertGreaterEqual(5, try_count)
                    continue
                else:
                    raise
            else:
                break
        client = socket.socket()
        client.connect(('127.0.0.1', port))
        client.send(b'xxx')
        proto = self.loop.run_until_complete(f_proto)
        proto.transport.close()
        client.close()

        f_proto = asyncio.Future(loop=self.loop)
        client = socket.socket(socket.AF_INET6)
        client.connect(('::1', port))
        client.send(b'xxx')
        proto = self.loop.run_until_complete(f_proto)
        proto.transport.close()
        client.close()

        server.close()
项目:azure-event-hubs-python    作者:Azure    | 项目源码 | 文件源码
def open(cls, owner=None):
        port = -1
        listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        for i in range(25672, 35672):
            port = i
            try:
                listener.bind(("127.0.0.1", port))
                break
            except socket.error as err:
                if err.errno != errno.EADDRINUSE:
                    log.error("%s: pipe socket bind failed %s", owner, err)
                    raise
        listener.listen(1)
        client = None
        server = None
        try:
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.setblocking(False)
            client.connect_ex(("127.0.0.1", port))
            server, address = listener.accept()
            log.info("%s: pipe accepted socket from %s", owner, address)
            client.setblocking(True)
            code = generate_uuid().bytes
            client.sendall(code)
            code2 = Pipe._recvall(server, len(code))
            if code != code2:
                raise IOError(errno.EIO, "Pipe handshake failed")

            pipe = Pipe()
            pipe.sink = client
            pipe.source = server
            return pipe
        except:
            if client:
                client.close()
            if server:
                server.close()
            raise
        finally:
            listener.close()
项目:nfcpy    作者:nfcpy    | 项目源码 | 文件源码
def _bind_socket(self, time_to_return):
        addr = ('0.0.0.0', self.addr[1])
        while time.time() < time_to_return:
            log.debug("trying to bind socket to %s:%d", *addr)
            try:
                self.socket.bind(addr)
                return True
            except socket.error as error:
                log.debug("bind failed with %s", error)
                if error.errno == errno.EADDRINUSE:
                    return False
                else:
                    raise error
项目:nfcpy    作者:nfcpy    | 项目源码 | 文件源码
def _bind_by_addr(self, socket, addr):
        if addr < 0 or addr > 63:
            raise err.Error(errno.EFAULT)
        with self.lock:
            if addr in range(32, 64) or isinstance(socket, tco.RawAccessPoint):
                if self.sap[addr] is None:
                    socket.bind(addr)
                    self.sap[addr] = ServiceAccessPoint(addr, self)
                    self.sap[addr].insert_socket(socket)
                else:
                    raise err.Error(errno.EADDRINUSE)
            else:
                raise err.Error(errno.EACCES)
项目:pytestlab    作者:sangoma    | 项目源码 | 文件源码
def new_rtp_socket(host, version=4):
    '''
    Get and return free socket address from the system in the rtp
    range 16382 <= port < 32767.

    Parameters
    ----------
    host : string
        hostname or ip for which a socket addr is needed

    Returns
    -------
    ip, port : string, int

    Notes
    -----
    Due to common usage with SIPp (which uses every rtp port
    and that port + 2) we have the rule that we skip forward
    by two on evey second call since N+2, (N+1)+2, will be
    already taken up and the next available will be (N+1)+2+1
    '''
    err = None
    for _ in range(5):
        try:
            return get_new_sock(
                host, port=next(_rtp_port_gen), version=version)
        except socket.error as e:
            # If we failed to bind, lets try again. Otherwise reraise
            # the error immediately as its something much more serious.
            if e.errno != errno.EADDRINUSE:
                raise
            err = e
    raise err
项目:networkzero    作者:tjguk    | 项目源码 | 文件源码
def _start_beacon(port=None):
    """Start a beacon thread within this process if no beacon is currently
    running on this machine.

    In general this is called automatically when an attempt is made to
    advertise or discover. It might be convenient, though, to call this
    function directly if you want to have a process whose only job is
    to host this beacon so that it doesn't shut down when other processes
    shut down.
    """
    global _beacon
    if _beacon is None:
        _logger.debug("About to start beacon with port %s", port)
        try:
            _beacon = _Beacon(port)
        except (OSError, socket.error) as exc:
            if exc.errno == errno.EADDRINUSE:
                _logger.warn("Beacon already active on this machine")
                #
                # _remote_beacon is simply a not-None sentinel value
                # to distinguish between the case where we have not
                # yet started a beacon and where we have found one
                # in another process.
                #
                _beacon = _remote_beacon
            else:
                raise
        else:
            _beacon.start()
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def handle(self, *args, **options):
        addrport = options['addrport']
        if ':' not in addrport:
            raise CommandError('Invalid addr:port specified: %s' % addrport)
        splitted = addrport.split(':')
        try:
            splitted[1] = int(splitted[1])
        except ValueError:
            raise CommandError('Invalid port specified: %s' % splitted[1])
        self.stdout.write('Check if toaster can listen on %s' % addrport)
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(tuple(splitted))
        except (socket.error, OverflowError) as err:
            errors = {
                errno.EACCES: 'You don\'t have permission to access port %s' \
                              % splitted[1],
                errno.EADDRINUSE: 'Port %s is already in use' % splitted[1],
                errno.EADDRNOTAVAIL: 'IP address can\'t be assigned to',
            }
            if hasattr(err, 'errno') and err.errno in errors:
                errtext = errors[err.errno]
            else:
                errtext = force_text(err)
            raise CommandError(errtext)

        self.stdout.write("OK")
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_rapid_restart(self):
        authkey = os.urandom(32)
        manager = QueueManager(
            address=('localhost', 0), authkey=authkey, serializer=SERIALIZER)
        srvr = manager.get_server()
        addr = srvr.address
        # Close the connection.Listener socket which gets opened as a part
        # of manager.get_server(). It's not needed for the test.
        srvr.listener.close()
        manager.start()

        p = self.Process(target=self._putter, args=(manager.address, authkey))
        p.daemon = True
        p.start()
        queue = manager.get_queue()
        self.assertEqual(queue.get(), 'hello world')
        del queue
        manager.shutdown()
        manager = QueueManager(
            address=addr, authkey=authkey, serializer=SERIALIZER)
        try:
            manager.start()
        except IOError as e:
            if e.errno != errno.EADDRINUSE:
                raise
            # Retry after some time, in case the old socket was lingering
            # (sporadic failure on buildbots)
            time.sleep(1.0)
            manager = QueueManager(
                address=addr, authkey=authkey, serializer=SERIALIZER)
        manager.shutdown()

#
#
#
项目:microProxy    作者:mike820324    | 项目源码 | 文件源码
def test_handle_stream_closed(self):
        self.layer.socks_conn = Mock()
        self.layer.socks_conn.send = Mock(side_effect=self.collect_send_event)

        socks_request = Request(
            REQ_COMMAND["CONNECT"], ADDR_TYPE["IPV4"],
            u"1.2.3.4", self.port)

        addr_not_support_status = RESP_STATUS["ADDRESS_TYPE_NOT_SUPPORTED"]
        network_unreach_status = RESP_STATUS["NETWORK_UNREACHABLE"]
        general_fail_status = RESP_STATUS["GENRAL_FAILURE"]

        error_cases = [
            (errno.ENOEXEC, addr_not_support_status),
            (errno.EBADF, addr_not_support_status),
            (errno.ETIMEDOUT, network_unreach_status),
            (errno.EADDRINUSE, general_fail_status),
            (55566, general_fail_status)]

        for code, expect_status in error_cases:
            self.layer.create_dest_stream = Mock(
                side_effect=self.create_raise_exception_function(
                    StreamClosedError((code, ))))
            result_future = self.layer.handle_request_and_create_destination(
                socks_request)
            with self.assertRaises(DestNotConnectedError):
                yield result_future

            self.assertIsNotNone(self.event)
            self.assertIsInstance(self.event, Response)
            self.assertEqual(self.event.status, expect_status)
            self.assertEqual(self.event.atyp, ADDR_TYPE["IPV4"])
            self.assertEqual(str(self.event.addr), "1.2.3.4")
            self.assertEqual(self.event.port, self.port)
项目:bitpay-brick    作者:javgh    | 项目源码 | 文件源码
def _init_server(self):
        # find our Bluetooth address
        self.bt_addr = self._find_local_bdaddr()
        self.bt_addr_queue.put(None)

        # find a free port; PORT_ANY does not seem to work correctly
        port_available = False
        server_sock = BluetoothSocket(RFCOMM)
        for port in range(1, 10):
            try:
                server_sock.bind((self.bt_addr, port))
                port_available = True
                break
            except Exception as e:  # IOError does not seem to catch the right exception
                if e[0] == errno.EADDRINUSE:
                    pass
                else:
                    raise e

        if not port_available:
            print 'No free bluetooth port found'
            return None

        server_sock.listen(1)
        port = server_sock.getsockname()[1]

        advertise_service( server_sock, self.service_desc
                         , service_id = self.service_uuid
                         , service_classes = [ self.service_uuid ]
                         , profiles = [ ]
                         )

        return server_sock
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_rapid_restart(self):
        authkey = os.urandom(32)
        manager = QueueManager(
            address=(test.support.HOST, 0), authkey=authkey, serializer=SERIALIZER)
        srvr = manager.get_server()
        addr = srvr.address
        # Close the connection.Listener socket which gets opened as a part
        # of manager.get_server(). It's not needed for the test.
        srvr.listener.close()
        manager.start()

        p = self.Process(target=self._putter, args=(manager.address, authkey))
        p.daemon = True
        p.start()
        queue = manager.get_queue()
        self.assertEqual(queue.get(), 'hello world')
        del queue
        manager.shutdown()
        manager = QueueManager(
            address=addr, authkey=authkey, serializer=SERIALIZER)
        try:
            manager.start()
        except OSError as e:
            if e.errno != errno.EADDRINUSE:
                raise
            # Retry after some time, in case the old socket was lingering
            # (sporadic failure on buildbots)
            time.sleep(1.0)
            manager = QueueManager(
                address=addr, authkey=authkey, serializer=SERIALIZER)
        manager.shutdown()

#
#
#
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_source_address(self):
        self.client.quit()
        port = support.find_unused_port()
        try:
            self.client.connect(self.server.host, self.server.port,
                                source_address=(HOST, port))
            self.assertEqual(self.client.sock.getsockname()[1], port)
            self.client.quit()
        except IOError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_source_address_passive_connection(self):
        port = support.find_unused_port()
        self.client.source_address = (HOST, port)
        try:
            with self.client.transfercmd('list') as sock:
                self.assertEqual(sock.getsockname()[1], port)
        except IOError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def testSourceAddress(self):
        # connect
        port = support.find_unused_port()
        try:
            smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
                    timeout=3, source_address=('127.0.0.1', port))
            self.assertEqual(smtp.source_address, ('127.0.0.1', port))
            self.assertEqual(smtp.local_hostname, 'localhost')
            smtp.quit()
        except IOError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def test__allocate_sockets_fail(self):
        """Test allocating sockets when all are taken.
        """
        # access protected module _allocate_sockets
        # pylint: disable=w0212

        socket.socket.bind.side_effect = socket.error(errno.EADDRINUSE,
                                                      'In use')

        with self.assertRaises(exc.ContainerSetupError):
            treadmill.runtime._allocate_sockets(
                'prod', '0.0.0.0', socket.SOCK_STREAM, 3
            )
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def _allocate_sockets(environment, host_ip, sock_type, count):
    """Return a list of `count` socket bound to an ephemeral port.
    """
    # TODO: this should probably be abstracted away
    if environment == 'prod':
        port_pool = six.moves.range(PROD_PORT_LOW, PROD_PORT_HIGH + 1)
    else:
        port_pool = six.moves.range(NONPROD_PORT_LOW, NONPROD_PORT_HIGH + 1)

    port_pool = random.sample(port_pool, PORT_SPAN)

    # socket objects are closed on GC so we need to return
    # them and expect the caller to keep them around while needed
    sockets = []

    for real_port in port_pool:
        if len(sockets) == count:
            break

        socket_ = socket.socket(socket.AF_INET, sock_type)
        try:
            socket_.bind((host_ip, real_port))
            if sock_type == socket.SOCK_STREAM:
                socket_.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                socket_.listen(0)
        except socket.error as err:
            if err.errno == errno.EADDRINUSE:
                continue
            raise

        sockets.append(socket_)
    else:
        raise exc.ContainerSetupError('{0} < {1}'.format(len(sockets), count),
                                      app_abort.AbortedReason.PORTS)

    return sockets
项目:BlueDot    作者:martinohanlon    | 项目源码 | 文件源码
def start(self):
        """
        Starts the Bluetooth server if its not already running. The server needs to be started before
        connections can be made.
        """
        if not self._running:

            if self._power_up_device:
                self.adapter.powered = True

            if not self.adapter.powered:
                raise Exception("Bluetooth device {} is turned off".format(self.adapter.device))

            #register the serial port profile with Bluetooth
            register_spp(self._port)

            #start Bluetooth server
            #open the Bluetooth socket
            self._server_sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
            self._server_sock.settimeout(BLUETOOTH_TIMEOUT)
            try:
                self._server_sock.bind((self.server_address, self.port))
            except (socket.error, OSError) as e:
                if e.errno == errno.EADDRINUSE:
                    print("Bluetooth address {} is already in use - is the server already running?".format(self.server_address))
                raise e
            self._server_sock.listen(1)

            #wait for client connection
            self._conn_thread = WrapThread(target=self._wait_for_connection)
            self._conn_thread.start()

            self._running = True
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def create_unix_server(self, protocol_factory, path=None, *,
                           sock=None, backlog=100, ssl=None):
        if isinstance(ssl, bool):
            raise TypeError('ssl argument must be an SSLContext or None')

        if path is not None:
            if sock is not None:
                raise ValueError(
                    'path and sock can not be specified at the same time')

            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

            try:
                sock.bind(path)
            except OSError as exc:
                sock.close()
                if exc.errno == errno.EADDRINUSE:
                    # Let's improve the error message by adding
                    # with what exact address it occurs.
                    msg = 'Address {!r} is already in use'.format(path)
                    raise OSError(errno.EADDRINUSE, msg) from None
                else:
                    raise
            except:
                sock.close()
                raise
        else:
            if sock is None:
                raise ValueError(
                    'path was not specified, and no sock specified')

            if sock.family != socket.AF_UNIX:
                raise ValueError(
                    'A UNIX Domain Socket was expected, got {!r}'.format(sock))

        server = base_events.Server(self, [sock])
        sock.listen(backlog)
        sock.setblocking(False)
        self._start_serving(protocol_factory, sock, ssl, server)
        return server
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_source_address(self):
        self.client.quit()
        port = support.find_unused_port()
        try:
            self.client.connect(self.server.host, self.server.port,
                                source_address=(HOST, port))
            self.assertEqual(self.client.sock.getsockname()[1], port)
            self.client.quit()
        except OSError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_source_address_passive_connection(self):
        port = support.find_unused_port()
        self.client.source_address = (HOST, port)
        try:
            with self.client.transfercmd('list') as sock:
                self.assertEqual(sock.getsockname()[1], port)
        except OSError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def testSourceAddress(self):
        # connect
        port = support.find_unused_port()
        try:
            smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
                    timeout=3, source_address=('127.0.0.1', port))
            self.assertEqual(smtp.source_address, ('127.0.0.1', port))
            self.assertEqual(smtp.local_hostname, 'localhost')
            smtp.quit()
        except OSError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_create_connection_local_addr_in_use(self):
        with test_utils.run_test_server() as httpd:
            f = self.loop.create_connection(
                lambda: MyProto(loop=self.loop),
                *httpd.address, local_addr=httpd.address)
            with self.assertRaises(OSError) as cm:
                self.loop.run_until_complete(f)
            self.assertEqual(cm.exception.errno, errno.EADDRINUSE)
            self.assertIn(str(httpd.address), cm.exception.strerror)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_create_server_dual_stack(self):
        f_proto = asyncio.Future(loop=self.loop)

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

        try_count = 0
        while True:
            try:
                port = support.find_unused_port()
                f = self.loop.create_server(TestMyProto, host=None, port=port)
                server = self.loop.run_until_complete(f)
            except OSError as ex:
                if ex.errno == errno.EADDRINUSE:
                    try_count += 1
                    self.assertGreaterEqual(5, try_count)
                    continue
                else:
                    raise
            else:
                break
        client = socket.socket()
        client.connect(('127.0.0.1', port))
        client.send(b'xxx')
        proto = self.loop.run_until_complete(f_proto)
        proto.transport.close()
        client.close()

        f_proto = asyncio.Future(loop=self.loop)
        client = socket.socket(socket.AF_INET6)
        client.connect(('::1', port))
        client.send(b'xxx')
        proto = self.loop.run_until_complete(f_proto)
        proto.transport.close()
        client.close()

        server.close()
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def run(self):
        """
        Sets up the live server and databases, and then loops over handling
        http requests.
        """
        if self.connections_override:
            # Override this thread's database connections with the ones
            # provided by the main thread.
            for alias, conn in self.connections_override.items():
                connections[alias] = conn
        try:
            # Create the handler for serving static and media files
            handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))

            # Go through the list of possible ports, hoping that we can find
            # one that is free to use for the WSGI server.
            for index, port in enumerate(self.possible_ports):
                try:
                    self.httpd = self._create_server(port)
                except socket.error as e:
                    if (index + 1 < len(self.possible_ports) and
                            e.errno == errno.EADDRINUSE):
                        # This port is already in use, so we go on and try with
                        # the next one in the list.
                        continue
                    else:
                        # Either none of the given ports are free or the error
                        # is something else than "Address already in use". So
                        # we let that error bubble up to the main thread.
                        raise
                else:
                    # A free port was found.
                    self.port = port
                    break

            self.httpd.set_app(handler)
            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set()
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def _start_all_fixed_port(self, host_ports):
    """Starts a server for each specified address with a fixed port.

    Does the work of actually trying to create a _SingleAddressWsgiServer for
    each specified address.

    Args:
      host_ports: An iterable of host, port tuples.

    Raises:
      BindError: The address could not be bound.
    """
    for host, port in host_ports:
      assert port != 0
      server = _SingleAddressWsgiServer((host, port), self._app)
      try:
        server.start()
      except BindError as bind_error:
        # TODO: I'm not sure about the behavior of quietly ignoring an
        # EADDRINUSE as long as the bind succeeds on at least one interface. I
        # think we should either:
        # - Fail (just like we do now when bind fails on every interface).
        # - Retry on next highest port.
        logging.debug('Failed to bind "%s:%s": %s', host, port, bind_error)
        continue
      else:
        self._servers.append(server)

    if not self._servers:
      raise BindError('Unable to bind %s:%s' % self.bind_addr)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def _start_all_dynamic_port(self, host_ports):
    """Starts a server for each specified address with a dynamic port.

    Does the work of actually trying to create a _SingleAddressWsgiServer for
    each specified address.

    Args:
      host_ports: An iterable of host, port tuples.

    Returns:
      The list of all servers (also saved as self._servers). A non empty list
      indicates success while an empty list indicates failure.
    """
    port = 0
    for host, _ in host_ports:
      server = _SingleAddressWsgiServer((host, port), self._app)
      try:
        server.start()
        if port == 0:
          port = server.port
      except BindError as bind_error:
        if bind_error[1][0] == errno.EADDRINUSE:
          # The port picked at random for first interface was not available
          # on one of the other interfaces. Forget them and try again.
          for server in self._servers:
            server.quit()
          self._servers = []
          break
        else:
          # Ignore the interface if we get an error other than EADDRINUSE.
          logging.debug('Failed to bind "%s:%s": %s', host, port, bind_error)
          continue
      else:
        self._servers.append(server)
    return self._servers
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def test_retry_eaddrinuse(self):
    inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    inet4_server_retry = self.mox.CreateMock(
        wsgi_server._SingleAddressWsgiServer)
    inet6_server_retry = self.mox.CreateMock(
        wsgi_server._SingleAddressWsgiServer)
    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                       socket.AI_PASSIVE).AndReturn(
                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
                            (None, None, None, None, ('::1', 0, 'baz'))])
    # First try
    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
        inet4_server)
    inet4_server.start()
    inet4_server.port = 123
    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
        inet6_server)
    inet6_server.start().AndRaise(
        wsgi_server.BindError('message', (errno.EADDRINUSE, 'in use')))
    inet4_server.quit()
    # Retry
    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
        inet4_server_retry)
    inet4_server_retry.start()
    inet4_server_retry.port = 456
    wsgi_server._SingleAddressWsgiServer(('::1', 456), None).AndReturn(
        inet6_server_retry)
    inet6_server_retry.start()
    self.mox.ReplayAll()
    self.server.start()
    self.mox.VerifyAll()
    self.assertItemsEqual([inet4_server_retry, inet6_server_retry],
                          self.server._servers)
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def check_socket(self):
        """Verify connection to ZBrushServer
        """

        if self.sock is None:
            return

        try:
            self.sock.send('check')
            if self.sock.recv(1024) == 'ok':
                # connected
                print 'connected!'
            else:
                # bad connection, clear socket
                self.status = False
                self.sock.close()
                self.sock = None
                print 'conn reset!'

        except socket.error as err:
            # catches server down errors, resets socket
            self.status = False
            self.sock.close()
            self.sock = None
            if errno.ECONNREFUSED in err:
                print 'conn ref'
                # server probably down
            if errno.EADDRINUSE in err:
                # this is fine
                print 'already connected...'
            if errno.EPIPE in err:
                # server down, or unexpected connection interuption
                print 'broken pipe, trying to reconnect'
        except AttributeError:
            print 'need new sock'
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def create_unix_server(self, protocol_factory, path=None, *,
                           sock=None, backlog=100, ssl=None):
        if isinstance(ssl, bool):
            raise TypeError('ssl argument must be an SSLContext or None')

        if path is not None:
            if sock is not None:
                raise ValueError(
                    'path and sock can not be specified at the same time')

            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

            try:
                sock.bind(path)
            except OSError as exc:
                sock.close()
                if exc.errno == errno.EADDRINUSE:
                    # Let's improve the error message by adding
                    # with what exact address it occurs.
                    msg = 'Address {!r} is already in use'.format(path)
                    raise OSError(errno.EADDRINUSE, msg) from None
                else:
                    raise
            except:
                sock.close()
                raise
        else:
            if sock is None:
                raise ValueError(
                    'path was not specified, and no sock specified')

            if sock.family != socket.AF_UNIX:
                raise ValueError(
                    'A UNIX Domain Socket was expected, got {!r}'.format(sock))

        server = base_events.Server(self, [sock])
        sock.listen(backlog)
        sock.setblocking(False)
        self._start_serving(protocol_factory, sock, ssl, server)
        return server
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_source_address(self):
        self.client.quit()
        port = support.find_unused_port()
        try:
            self.client.connect(self.server.host, self.server.port,
                                source_address=(HOST, port))
            self.assertEqual(self.client.sock.getsockname()[1], port)
            self.client.quit()
        except OSError as e:
            if e.errno == errno.EADDRINUSE:
                self.skipTest("couldn't bind to port %d" % port)
            raise