Python twisted.application.internet.UDPServer() Examples

The following are 19 code examples of twisted.application.internet.UDPServer(). 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.application.internet , or try the search function .
Example #1
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_UDP(self):
        """
        Test L{internet.UDPServer} with a random port: starting the service
        should give it valid port, and stopService should free it so that we
        can start a server on the same port again.
        """
        if not interfaces.IReactorUDP(reactor, None):
            raise unittest.SkipTest("This reactor does not support UDP sockets")
        p = protocol.DatagramProtocol()
        t = internet.UDPServer(0, p)
        t.startService()
        num = t._port.getHost().port
        self.assertNotEqual(num, 0)
        def onStop(ignored):
            t = internet.UDPServer(num, p)
            t.startService()
            return t.stopService()
        return defer.maybeDeferred(t.stopService).addCallback(onStop) 
Example #2
Source File: tftp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def updateServers(self):
        """Run a server on every interface.

        For each configured network interface this will start a TFTP
        server. If called later it will bring up servers on newly
        configured interfaces and bring down servers on deconfigured
        interfaces.
        """
        addrs_established = set(service.name for service in self.getServers())
        addrs_desired = set(get_all_interface_addresses())

        for address in addrs_desired - addrs_established:
            if not IPAddress(address).is_link_local():
                tftp_service = UDPServer(
                    self.port,
                    TransferTimeTrackingTFTP(self.backend),
                    interface=address,
                )
                tftp_service.setName(address)
                tftp_service.setServiceParent(self)

        for address in addrs_established - addrs_desired:
            tftp_service = self.getServiceNamed(address)
            tftp_service.disownServiceParent() 
Example #3
Source File: tap.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def makeService(config):
    import client, cache, hosts

    ca, cl = [], []
    if config['cache']:
        ca.append(cache.CacheResolver(verbose=config['verbose']))
    if config['recursive']:
        cl.append(client.createResolver(resolvconf=config['resolv-conf']))
    if config['hosts-file']:
        cl.append(hosts.Resolver(file=config['hosts-file']))

    f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
    p = dns.DNSDatagramProtocol(f)
    f.noisy = 0
    ret = service.MultiService()
    for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
        s = klass(config['port'], arg, interface=config['interface'])
        s.setServiceParent(ret)
    for svc in config.svcs:
        svc.setServiceParent(ret)
    return ret 
Example #4
Source File: test_application.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_UDP(self):
        """
        Test L{internet.UDPServer} with a random port: starting the service
        should give it valid port, and stopService should free it so that we
        can start a server on the same port again.
        """
        if not interfaces.IReactorUDP(reactor, None):
            raise unittest.SkipTest("This reactor does not support UDP sockets")
        p = protocol.DatagramProtocol()
        t = internet.UDPServer(0, p)
        t.startService()
        num = t._port.getHost().port
        self.assertNotEquals(num, 0)
        def onStop(ignored):
            t = internet.UDPServer(num, p)
            t.startService()
            return t.stopService()
        return defer.maybeDeferred(t.stopService).addCallback(onStop) 
Example #5
Source File: tap.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def makeService(config):
    import client, cache, hosts

    ca, cl = [], []
    if config['cache']:
        ca.append(cache.CacheResolver(verbose=config['verbose']))
    if config['recursive']:
        cl.append(client.createResolver(resolvconf=config['resolv-conf']))
    if config['hosts-file']:
        cl.append(hosts.Resolver(file=config['hosts-file']))

    f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
    p = dns.DNSDatagramProtocol(f)
    f.noisy = 0
    ret = service.MultiService()
    for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
        s = klass(config['port'], arg, interface=config['interface'])
        s.setServiceParent(ret)
    for svc in config.svcs:
        svc.setServiceParent(ret)
    return ret 
Example #6
Source File: __init__.py    From opencanary with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getService(self):
        """Return service to be run

        This handles the easy case where the CanaryService class is
        also the Factory/Datagram class. Subclasses should override
        this if more intricracy is needed.
        """
        if isinstance(self, Factory):
            return internet.TCPServer(self.port, self)
        elif isinstance(self, DatagramProtocol):
            return internet.UDPServer(self.port, self)

        err = 'The class %s does not inherit from either Factory or DatagramProtocol.' % (
            self.__class__.__name__
            )
        raise Exception(err) 
Example #7
Source File: test_application.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_UDP(self):
        """
        Test L{internet.UDPServer} with a random port: starting the service
        should give it valid port, and stopService should free it so that we
        can start a server on the same port again.
        """
        if not interfaces.IReactorUDP(reactor, None):
            raise unittest.SkipTest("This reactor does not support UDP sockets")
        p = protocol.DatagramProtocol()
        t = internet.UDPServer(0, p)
        t.startService()
        num = t._port.getHost().port
        self.assertNotEqual(num, 0)
        def onStop(ignored):
            t = internet.UDPServer(num, p)
            t.startService()
            return t.stopService()
        return defer.maybeDeferred(t.stopService).addCallback(onStop) 
Example #8
Source File: ntp.py    From opencanary with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getService(self):
        f = MiniNtp()
        f.factory = self
        return internet.UDPServer(self.port, f, interface=self.listen_addr) 
Example #9
Source File: tftp.py    From opencanary with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getService(self):
        f = Tftp()
        f.factory = self
        return internet.UDPServer(self.port, f, interface=self.listen_addr) 
Example #10
Source File: sip.py    From opencanary with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getService(self):
        f = SIPServer()
        f.factory = self
        return internet.UDPServer(self.port, f, interface=self.listen_addr) 
Example #11
Source File: snmp.py    From opencanary with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getService(self):
        f = MiniSNMP()
        f.factory = self
        return internet.UDPServer(self.port, f, interface=self.listen_addr) 
Example #12
Source File: compat.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def listenUDP(self, port, proto, interface='', maxPacketSize=8192):
        s = internet.UDPServer(port, proto, interface, maxPacketSize)
        s.privileged = 1
        s.setServiceParent(self.app) 
Example #13
Source File: tap.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def makeService(config):
    ca, cl = _buildResolvers(config)

    f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
    p = dns.DNSDatagramProtocol(f)
    f.noisy = 0
    ret = service.MultiService()
    for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
        s = klass(config['port'], arg, interface=config['interface'])
        s.setServiceParent(ret)
    for svc in config.svcs:
        svc.setServiceParent(ret)
    return ret 
Example #14
Source File: tftp.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _getPort(self):
        """See :py:meth:`twisted.application.internet.UDPServer._getPort`."""
        return self._listenUDP(*self.args, **self.kwargs) 
Example #15
Source File: tftp.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def getServers(self):
        """Return a set of all configured servers.

        :rtype: :class:`set` of :class:`internet.UDPServer`
        """
        return {service for service in self if service is not self.refresher} 
Example #16
Source File: tap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def makeService(config):
    ca, cl = _buildResolvers(config)

    f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
    p = dns.DNSDatagramProtocol(f)
    f.noisy = 0
    ret = service.MultiService()
    for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
        s = klass(config['port'], arg, interface=config['interface'])
        s.setServiceParent(ret)
    for svc in config.svcs:
        svc.setServiceParent(ret)
    return ret 
Example #17
Source File: test_tftp.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_getPort_calls__listenUDP_with_args_from_constructor(self):
        server = UDPServer(sentinel.foo, bar=sentinel.bar)
        _listenUDP = self.patch(server, "_listenUDP")
        _listenUDP.return_value = sentinel.port
        self.assertEqual(sentinel.port, server._getPort())
        self.assertThat(
            _listenUDP, MockCalledOnceWith(sentinel.foo, bar=sentinel.bar)
        ) 
Example #18
Source File: test_tftp.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_listenUDP_with_IPv6_address(self):
        server = UDPServer(0, DummyProtocol(), "::1")
        port = server._getPort()
        self.addCleanup(port.stopListening)
        self.assertEqual(AF_INET6, port.addressFamily) 
Example #19
Source File: test_tftp.py    From maas with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_tftp_service(self):
        # A TFTP service is configured and added to the top-level service.
        interfaces = [factory.make_ipv4_address(), factory.make_ipv6_address()]
        self.patch(
            tftp_module, "get_all_interface_addresses", lambda: interfaces
        )
        example_root = self.make_dir()
        example_client_service = Mock()
        example_port = factory.pick_port()
        tftp_service = TFTPService(
            resource_root=example_root,
            client_service=example_client_service,
            port=example_port,
        )
        tftp_service.updateServers()
        # The "tftp" service is a multi-service containing UDP servers for
        # each interface defined by get_all_interface_addresses().
        self.assertIsInstance(tftp_service, MultiService)
        # There's also a TimerService that updates the servers every 45s.
        self.assertThat(
            tftp_service.refresher,
            MatchesStructure.byEquality(
                step=45,
                parent=tftp_service,
                name="refresher",
                call=(tftp_service.updateServers, (), {}),
            ),
        )
        expected_backend = MatchesAll(
            IsInstance(TFTPBackend),
            AfterPreprocessing(
                lambda backend: backend.base.path, Equals(example_root)
            ),
            AfterPreprocessing(
                lambda backend: backend.client_service,
                Equals(example_client_service),
            ),
        )
        expected_protocol = MatchesAll(
            IsInstance(TFTP),
            AfterPreprocessing(
                lambda protocol: protocol.backend, expected_backend
            ),
        )
        expected_server = MatchesAll(
            IsInstance(internet.UDPServer),
            AfterPreprocessing(lambda service: len(service.args), Equals(2)),
            AfterPreprocessing(
                lambda service: service.args[0], Equals(example_port)  # port
            ),
            AfterPreprocessing(
                lambda service: service.args[1], expected_protocol  # protocol
            ),
        )
        self.assertThat(tftp_service.getServers(), AllMatch(expected_server))
        # Only the interface used for each service differs.
        self.assertItemsEqual(
            [svc.kwargs for svc in tftp_service.getServers()],
            [{"interface": interface} for interface in interfaces],
        )