Python twisted.internet.error.CannotListenError() Examples

The following are 30 code examples of twisted.internet.error.CannotListenError(). 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 twisted.internet.error , or try the search function .
Example #1
Source File: test_client.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_runOutOfFiles(self):
        """
        If the process is out of files, L{Resolver._connectedProtocol}
        will give up.
        """
        ports = []

        class FakeReactor(object):
            def listenUDP(self, port, *args, **kwargs):
                ports.append(port)
                err = OSError(errno.EMFILE, "Out of files :(")
                raise CannotListenError(None, port, err)

        resolver = client.Resolver(servers=[('example.com', 53)])
        resolver._reactor = FakeReactor()

        exc = self.assertRaises(CannotListenError, resolver._connectedProtocol)
        # The EMFILE-containing exception was raised, and it did not try
        # multiple times.
        self.assertEqual(exc.socketError.errno, errno.EMFILE)
        self.assertEqual(len(ports), 1) 
Example #2
Source File: test_tcp.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testCannotBind(self):
        f = MyServerFactory()

        p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
        n = p1.getHost().port
        self.ports.append(p1)
        dest = p1.getHost()
        self.assertEquals(dest.type, "TCP")
        self.assertEquals(dest.host, "127.0.0.1")
        self.assertEquals(dest.port, n)
        
        # make sure new listen raises error
        self.assertRaises(error.CannotListenError,
                          reactor.listenTCP, n, f, interface='127.0.0.1')

        return self.cleanPorts(*self.ports) 
Example #3
Source File: test_names.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.factory = server.DNSServerFactory([
            test_domain_com, reverse_domain, my_domain_com
        ], verbose=2)

        p = dns.DNSDatagramProtocol(self.factory)

        while 1:
            self.listenerTCP = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
            port = self.listenerTCP.getHost().port

            try:
                self.listenerUDP = reactor.listenUDP(port, p, interface="127.0.0.1")
            except error.CannotListenError:
                self.listenerTCP.stopListening()
            else:
                break

        self.resolver = client.Resolver(servers=[('127.0.0.1', port)]) 
Example #4
Source File: test_streamedlogs.py    From gridsync with GNU General Public License v3.0 6 votes vote down vote up
def fake_log_server(protocol):
    from twisted.internet import reactor

    while True:
        port_number = randrange(10000, 60000)
        # Why do you make me know the port number in advance, Autobahn?
        factory = WebSocketServerFactory(
            "ws://127.0.0.1:{}".format(port_number)
        )
        factory.protocol = protocol

        try:
            server_port = reactor.listenTCP(port_number, factory)
        except CannotListenError as e:
            if e.socketError.errno == EADDRINUSE:
                continue
            raise
        else:
            break

    return server_port 
Example #5
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_endpointListenFailure(self):
        """
        When an endpoint tries to listen on an already listening port, a
        C{CannotListenError} failure is errbacked.
        """
        factory = object()
        exception = error.CannotListenError('', 80, factory)
        mreactor = RaisingMemoryReactor(listenException=exception)

        ep, ignoredArgs, ignoredDest = self.createServerEndpoint(
            mreactor, factory)

        d = ep.listen(object())

        receivedExceptions = []

        def checkFailure(f):
            receivedExceptions.append(f.value)

        d.addErrback(checkFailure)

        self.assertEquals(receivedExceptions, [exception]) 
Example #6
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_endpointListenFailure(self):
        """
        When an endpoint tries to listen on an already listening port, a
        C{CannotListenError} failure is errbacked.
        """
        factory = object()
        exception = error.CannotListenError('', 80, factory)
        mreactor = RaisingMemoryReactor(listenException=exception)

        ep, ignoredArgs, ignoredDest = self.createServerEndpoint(
            mreactor, factory)

        d = ep.listen(object())

        receivedExceptions = []

        def checkFailure(f):
            receivedExceptions.append(f.value)

        d.addErrback(checkFailure)

        self.assertEqual(receivedExceptions, [exception]) 
Example #7
Source File: test_client.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_disallowedPort(self):
        """
        If a port number is initially selected which cannot be bound, the
        L{CannotListenError} is handled and another port number is attempted.
        """
        ports = []

        class FakeReactor(object):
            def listenUDP(self, port, *args, **kwargs):
                ports.append(port)
                if len(ports) == 1:
                    raise CannotListenError(None, port, None)

        resolver = client.Resolver(servers=[('example.com', 53)])
        resolver._reactor = FakeReactor()

        resolver._connectedProtocol()
        self.assertEqual(len(set(ports)), 2) 
Example #8
Source File: udp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _bindSocket(self):
        try:
            skt = self.createSocket()
            skt.bind((self.interface, self.port))
        except socket.error as le:
            raise error.CannotListenError(self.interface, self.port, le)

        # Make sure that if we listened on port 0, we update that to
        # reflect what the OS actually assigned us.
        self._realPortNumber = skt.getsockname()[1]

        log.msg("%s starting on %s" % (
                self._getLogPrefix(self.protocol), self._realPortNumber))

        self.connected = True
        self.socket = skt
        self.getFileHandle = self.socket.fileno 
Example #9
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_cannotBind(self):
        """
        L{IReactorTCP.listenTCP} raises L{error.CannotListenError} if the
        address to listen on is already in use.
        """
        f = MyServerFactory()

        p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
        self.addCleanup(p1.stopListening)
        n = p1.getHost().port
        dest = p1.getHost()
        self.assertEqual(dest.type, "TCP")
        self.assertEqual(dest.host, "127.0.0.1")
        self.assertEqual(dest.port, n)

        # make sure new listen raises error
        self.assertRaises(error.CannotListenError,
                          reactor.listenTCP, n, f, interface='127.0.0.1') 
Example #10
Source File: test_udp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_bindError(self):
        """
        A L{CannotListenError} exception is raised when attempting to bind a
        second protocol instance to an already bound port
        """
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        port = reactor.listenUDP(0, server, interface='127.0.0.1')

        def cbStarted(ignored):
            self.assertEqual(port.getHost(), server.transport.getHost())
            server2 = Server()
            self.assertRaises(
                error.CannotListenError,
                reactor.listenUDP, port.getHost().port, server2,
                interface='127.0.0.1')
        d.addCallback(cbStarted)

        def cbFinished(ignored):
            return port.stopListening()
        d.addCallback(cbFinished)
        return d 
Example #11
Source File: test_unix.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_socketLocking(self):
        """
        L{IReactorUNIX.listenUNIX} raises L{error.CannotListenError} if passed
        the name of a file on which a server is already listening.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)

        self.assertRaises(
            error.CannotListenError,
            reactor.listenUNIX, filename, serverFactory, wantPID=True)

        def stoppedListening(ign):
            unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)
            return unixPort.stopListening()

        return unixPort.stopListening().addCallback(stoppedListening) 
Example #12
Source File: test_udp.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testBindError(self):
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        port = reactor.listenUDP(0, server, interface='127.0.0.1')

        def cbStarted(ignored):
            self.assertEquals(port.getHost(), server.transport.getHost())

            server2 = Server()
            self.assertRaises(
                error.CannotListenError,
                reactor.listenUDP, port.getHost().port, server2,
                interface='127.0.0.1')
        d.addCallback(cbStarted)

        def cbFinished(ignored):
            return port.stopListening()
        d.addCallback(cbFinished)
        return d 
Example #13
Source File: tuntap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _bindSocket(self):
        """
        Open the tunnel.
        """
        log.msg(
            format="%(protocol)s starting on %(interface)s",
            protocol=self.protocol.__class__,
            interface=self.interface)
        try:
            fileno, interface = self._openTunnel(
                self.interface, self._mode | TunnelFlags.IFF_NO_PI)
        except (IOError, OSError) as e:
            raise error.CannotListenError(None, self.interface, e)

        self.interface = interface
        self._fileno = fileno

        self.connected = 1 
Example #14
Source File: tuntap.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _bindSocket(self):
        """
        Open the tunnel.
        """
        log.msg(
            format="%(protocol)s starting on %(interface)s",
            protocol=self.protocol.__class__,
            interface=self.interface)
        try:
            fileno, interface = self._openTunnel(
                self.interface, self._mode | TunnelFlags.IFF_NO_PI)
        except (IOError, OSError) as e:
            raise error.CannotListenError(None, self.interface, e)

        self.interface = interface
        self._fileno = fileno

        self.connected = 1 
Example #15
Source File: test_ftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_portRange(self):
        """
        L{FTP.passivePortRange} should determine the ports which
        L{FTP.getDTPPort} attempts to bind. If no port from that iterator can
        be bound, L{error.CannotListenError} should be raised, otherwise the
        first successful result from L{FTP.listenFactory} should be returned.
        """
        def listenFactory(portNumber, factory):
            if portNumber in (22032, 22033, 22034):
                raise error.CannotListenError('localhost', portNumber, 'error')
            return portNumber
        self.serverProtocol.listenFactory = listenFactory

        port = self.serverProtocol.getDTPPort(protocol.Factory())
        self.assertEqual(port, 0)

        self.serverProtocol.passivePortRange = range(22032, 65536)
        port = self.serverProtocol.getDTPPort(protocol.Factory())
        self.assertEqual(port, 22035)

        self.serverProtocol.passivePortRange = range(22032, 22035)
        self.assertRaises(error.CannotListenError,
                          self.serverProtocol.getDTPPort,
                          protocol.Factory()) 
Example #16
Source File: udp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _bindSocket(self):
        try:
            skt = self.createSocket()
            skt.bind((self.interface, self.port))
        except socket.error as le:
            raise error.CannotListenError(self.interface, self.port, le)

        # Make sure that if we listened on port 0, we update that to
        # reflect what the OS actually assigned us.
        self._realPortNumber = skt.getsockname()[1]

        log.msg("%s starting on %s" % (
                self._getLogPrefix(self.protocol), self._realPortNumber))

        self.connected = True
        self.socket = skt
        self.getFileHandle = self.socket.fileno 
Example #17
Source File: client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _connectedProtocol(self):
        """
        Return a new L{DNSDatagramProtocol} bound to a randomly selected port
        number.
        """
        if 'protocol' in self.__dict__:
            # Some code previously asked for or set the deprecated `protocol`
            # attribute, so it probably expects that object to be used for
            # queries.  Give it back and skip the super awesome source port
            # randomization logic.  This is actually a really good reason to
            # remove this deprecated backward compatibility as soon as
            # possible. -exarkun
            return self.protocol
        proto = dns.DNSDatagramProtocol(self)
        while True:
            try:
                self._reactor.listenUDP(dns.randomSource(), proto)
            except error.CannotListenError:
                pass
            else:
                return proto 
Example #18
Source File: test_ftp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_portRange(self):
        """
        L{FTP.passivePortRange} should determine the ports which
        L{FTP.getDTPPort} attempts to bind. If no port from that iterator can
        be bound, L{error.CannotListenError} should be raised, otherwise the
        first successful result from L{FTP.listenFactory} should be returned.
        """
        def listenFactory(portNumber, factory):
            if portNumber in (22032, 22033, 22034):
                raise error.CannotListenError('localhost', portNumber, 'error')
            return portNumber
        self.serverProtocol.listenFactory = listenFactory

        port = self.serverProtocol.getDTPPort(protocol.Factory())
        self.assertEquals(port, 0)

        self.serverProtocol.passivePortRange = xrange(22032, 65536)
        port = self.serverProtocol.getDTPPort(protocol.Factory())
        self.assertEquals(port, 22035)

        self.serverProtocol.passivePortRange = xrange(22032, 22035)
        self.assertRaises(error.CannotListenError,
                          self.serverProtocol.getDTPPort,
                          protocol.Factory()) 
Example #19
Source File: test_unix.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_socketLocking(self):
        """
        L{IReactorUNIX.listenUNIX} raises L{error.CannotListenError} if passed
        the name of a file on which a server is already listening.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)

        self.assertRaises(
            error.CannotListenError,
            reactor.listenUNIX, filename, serverFactory, wantPID=True)

        def stoppedListening(ign):
            unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)
            return unixPort.stopListening()

        return unixPort.stopListening().addCallback(stoppedListening) 
Example #20
Source File: test_unix.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_socketLocking(self):
        """
        L{IReactorUNIX.listenUNIX} raises L{error.CannotListenError} if passed
        the name of a file on which a server is already listening.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)

        self.assertRaises(
            error.CannotListenError,
            reactor.listenUNIX, filename, serverFactory, wantPID=True)

        def stoppedListening(ign):
            unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)
            return unixPort.stopListening()

        return unixPort.stopListening().addCallback(stoppedListening) 
Example #21
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_endpointListenFailure(self):
        """
        When an endpoint tries to listen on an already listening port, a
        C{CannotListenError} failure is errbacked.
        """
        factory = object()
        exception = error.CannotListenError('', 80, factory)
        mreactor = RaisingMemoryReactor(listenException=exception)

        ep, ignoredArgs, ignoredDest = self.createServerEndpoint(
            mreactor, factory)

        d = ep.listen(object())

        receivedExceptions = []

        def checkFailure(f):
            receivedExceptions.append(f.value)

        d.addErrback(checkFailure)

        self.assertEqual(receivedExceptions, [exception]) 
Example #22
Source File: test_udp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testBindError(self):
        server = Server()
        d = server.startedDeferred = defer.Deferred()
        port = reactor.listenUDP(0, server, interface='127.0.0.1')

        def cbStarted(ignored):
            self.assertEquals(port.getHost(), server.transport.getHost())

            server2 = Server()
            self.assertRaises(
                error.CannotListenError,
                reactor.listenUDP, port.getHost().port, server2,
                interface='127.0.0.1')
        d.addCallback(cbStarted)

        def cbFinished(ignored):
            return port.stopListening()
        d.addCallback(cbFinished)
        return d 
Example #23
Source File: test_tcp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_cannotBind(self):
        """
        L{IReactorTCP.listenTCP} raises L{error.CannotListenError} if the
        address to listen on is already in use.
        """
        f = MyServerFactory()

        p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
        self.addCleanup(p1.stopListening)
        n = p1.getHost().port
        dest = p1.getHost()
        self.assertEquals(dest.type, "TCP")
        self.assertEquals(dest.host, "127.0.0.1")
        self.assertEquals(dest.port, n)

        # make sure new listen raises error
        self.assertRaises(error.CannotListenError,
                          reactor.listenTCP, n, f, interface='127.0.0.1') 
Example #24
Source File: test_client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_disallowedPort(self):
        """
        If a port number is initially selected which cannot be bound, the
        L{CannotListenError} is handled and another port number is attempted.
        """
        ports = []

        class FakeReactor(object):
            def listenUDP(self, port, *args):
                ports.append(port)
                if len(ports) == 1:
                    raise error.CannotListenError(None, port, None)

        resolver = client.Resolver(servers=[('example.com', 53)])
        resolver._reactor = FakeReactor()

        proto = resolver._connectedProtocol()
        self.assertEqual(len(set(ports)), 2) 
Example #25
Source File: test_tcp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_cannotBind(self):
        """
        L{IReactorTCP.listenTCP} raises L{error.CannotListenError} if the
        address to listen on is already in use.
        """
        f = MyServerFactory()

        p1 = reactor.listenTCP(0, f, interface='127.0.0.1')
        self.addCleanup(p1.stopListening)
        n = p1.getHost().port
        dest = p1.getHost()
        self.assertEqual(dest.type, "TCP")
        self.assertEqual(dest.host, "127.0.0.1")
        self.assertEqual(dest.port, n)

        # make sure new listen raises error
        self.assertRaises(error.CannotListenError,
                          reactor.listenTCP, n, f, interface='127.0.0.1') 
Example #26
Source File: test_client.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_disallowedPort(self):
        """
        If a port number is initially selected which cannot be bound, the
        L{CannotListenError} is handled and another port number is attempted.
        """
        ports = []

        class FakeReactor(object):
            def listenUDP(self, port, *args, **kwargs):
                ports.append(port)
                if len(ports) == 1:
                    raise CannotListenError(None, port, None)

        resolver = client.Resolver(servers=[('example.com', 53)])
        resolver._reactor = FakeReactor()

        resolver._connectedProtocol()
        self.assertEqual(len(set(ports)), 2) 
Example #27
Source File: test_client.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_disallowedPortRepeatedly(self):
        """
        If port numbers that cannot be bound are repeatedly selected,
        L{resolver._connectedProtocol} will give up eventually.
        """
        ports = []

        class FakeReactor(object):
            def listenUDP(self, port, *args, **kwargs):
                ports.append(port)
                raise CannotListenError(None, port, None)

        resolver = client.Resolver(servers=[('example.com', 53)])
        resolver._reactor = FakeReactor()

        self.assertRaises(CannotListenError, resolver._connectedProtocol)
        # 1000 is a good round number. I like it.
        self.assertEqual(len(ports), 1000) 
Example #28
Source File: test_ftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_portRange(self):
        """
        L{FTP.passivePortRange} should determine the ports which
        L{FTP.getDTPPort} attempts to bind. If no port from that iterator can
        be bound, L{error.CannotListenError} should be raised, otherwise the
        first successful result from L{FTP.listenFactory} should be returned.
        """
        def listenFactory(portNumber, factory):
            if portNumber in (22032, 22033, 22034):
                raise error.CannotListenError('localhost', portNumber, 'error')
            return portNumber
        self.serverProtocol.listenFactory = listenFactory

        port = self.serverProtocol.getDTPPort(protocol.Factory())
        self.assertEqual(port, 0)

        self.serverProtocol.passivePortRange = xrange(22032, 65536)
        port = self.serverProtocol.getDTPPort(protocol.Factory())
        self.assertEqual(port, 22035)

        self.serverProtocol.passivePortRange = xrange(22032, 22035)
        self.assertRaises(error.CannotListenError,
                          self.serverProtocol.getDTPPort,
                          protocol.Factory()) 
Example #29
Source File: udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _bindSocket(self):
        try:
            skt = self.createInternetSocket()
            skt.bind((self.interface, self.port))
        except socket.error, le:
            raise error.CannotListenError, (self.interface, self.port, le)

        # Make sure that if we listened on port 0, we update that to
        # reflect what the OS actually assigned us. 
Example #30
Source File: unix.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def startListening(self):
        """Create and bind my socket, and begin listening on it.

        This is called on unserialization, and must be called after creating a
        server to begin listening on the specified port.
        """
        log.msg("%s starting on %r" % (self.factory.__class__, repr(self.port)))
        if self.wantPID:
            self.lockFile = lockfile.FilesystemLock(self.port + ".lock")
            if not self.lockFile.lock():
                raise CannotListenError, (None, self.port, "Cannot acquire lock")
            else:
                if not self.lockFile.clean:
                    try:
                        # This is a best-attempt at cleaning up
                        # left-over unix sockets on the filesystem.
                        # If it fails, there's not much else we can
                        # do.  The bind() below will fail with an
                        # exception that actually propegates.
                        if stat.S_ISSOCK(os.stat(self.port).st_mode):
                            os.remove(self.port)
                    except:
                        pass

        self.factory.doStart()
        try:
            skt = self.createInternetSocket()
            skt.bind(self.port)
        except socket.error, le:
            raise CannotListenError, (None, self.port, le)