Python twisted.internet.reactor.listenMulticast() Examples

The following are 21 code examples of twisted.internet.reactor.listenMulticast(). 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.reactor , or try the search function .
Example #1
Source File: __init__.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def setup_udp(self):
        reactor.listenMulticast(self.udp_port, MeshUdpProtocol(self), listenMultiple=True) 
Example #2
Source File: ssdp_server.py    From motion-notify with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, interface='', status_port=0, device_target=''):
        self.interface = interface
        self.device_target = device_target
        self.status_port = status_port
        self.port = reactor.listenMulticast(SSDP_PORT, self, listenMultiple=True) # pylint: disable=no-member
        self.port.joinGroup(SSDP_ADDR, interface=interface)
        reactor.addSystemEventTrigger('before', 'shutdown', self.stop) # pylint: disable=no-member 
Example #3
Source File: main.py    From dtella with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        core.DtellaMain_Base.__init__(self)

        # Location map: ipp->string, usually only contains 1 entry
        self.location = {}

        # This shuts down the Dtella node after a period of inactivity.
        self.disconnect_dcall = None

        # Login counter (just for eye candy)
        self.login_counter = 0
        self.login_text = ""

        # DC Handler(s)
        self.dch = None
        self.pending_dch = None

        # Nick used for passive-mode transfer aborting
        self.abort_nick = None

        # Peer Handler
        try:
            import dtella.client.bridge_client as bridge_client
        except ImportError:
            self.ph = core.PeerHandler(self)
        else:
            self.ph = bridge_client.BridgeClientProtocol(self)

        # Peer discovery handler
        print "LISTENING FOR PEERS"
        self.pdh = core.PeerDiscovery(self)
        reactor.listenMulticast(8005, self.pdh, listenMultiple=True)

        # State Manager
        self.state = dtella.common.state.StateManager(
            self, STATE_FILE, dtella.common.state.client_loadsavers)
        self.state.initLoad()

        # DNS Handler
        self.dcfg = dtella.client.pull_dconfig.DynamicConfigPuller(self) 
Example #4
Source File: service_discovery_ssdp.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def start(self):
        dserver = defer.Deferred()
        dclient = defer.Deferred()
        try:
            self.ssdp = reactor.listenMulticast(SSDP_PORT,
                                                ServerBase(self._node_id,
                                                           self._control_uri,
                                                           self.iface_send_list,
                                                           d=dserver
                                                          ),
                                                listenMultiple=True)
            self.ssdp.setTTL(5)
            for iface_ in self.iface_send_list:
                d = self.ssdp.joinGroup(SSDP_ADDR, interface=iface_)
                d.addErrback(lambda x: _log.error("Failed to join multicast group %s:%s, %s", iface_, SSDP_PORT, x))
                d.addCallback(lambda x: _log.debug("Joined multicast group %s:%s, %s", iface_, SSDP_PORT, x))
        except:
            _log.exception("Multicast listen join failed!!")
            # Dont start server some one is alerady running locally

        # TODO: Do we need this ?
        self.port = reactor.listenMulticast(0, ClientBase(dclient=dclient), interface=self.iface)
        _log.debug("SSDP Host: %s" % repr(self.port.getHost()))

        # Set ignore port and ips
        if self.ssdp and self.ignore_self:
            self.ssdp.protocol.set_ignore_list([(x, self.port.getHost().port) for x in self.iface_send_list])

        return dserver, dclient 
Example #5
Source File: service_discovery_ssdp.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def start(self):
        dserver = defer.Deferred()
        dclient = defer.Deferred()
        try:
            self.ssdp = reactor.listenMulticast(SSDP_PORT,
                                                ServerBase(self._node_id,
                                                           self._control_uri,
                                                           self.iface_send_list,
                                                           d=dserver),
                                                listenMultiple=True)
            self.ssdp.setTTL(5)
            for iface_ in self.iface_send_list:
                d = self.ssdp.joinGroup(SSDP_ADDR, interface=iface_)
                d.addErrback(lambda x: _log.error("Failed to join multicast group %s:%s, %s", iface_, SSDP_PORT, x))
                d.addCallback(lambda x: _log.debug("Joined multicast group %s:%s, %s", iface_, SSDP_PORT, x))
        except:
            _log.exception("Multicast listen join failed!!")
            # Dont start server some one is alerady running locally

        # TODO: Do we need this ?
        self.port = reactor.listenMulticast(0, ClientBase(d=dclient), interface=self.iface)
        _log.debug("SSDP Host: %s" % repr(self.port.getHost()))

        # Set ignore port and ips
        if self.ssdp and self.ignore_self:
            self.ssdp.protocol.set_ignore_list([(x, self.port.getHost().port) for x in self.iface_send_list])

        return dserver, dclient 
Example #6
Source File: test_udp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testMultiListen(self):
        c = Server()
        p = reactor.listenMulticast(0, c, listenMultiple=True)
        self.runUntilSuccess(self.server.transport.joinGroup, "225.0.0.250")
        portno = p.getHost().port
        c2 = Server()
        p2 = reactor.listenMulticast(portno, c2, listenMultiple=True)
        self.runUntilSuccess(self.server.transport.joinGroup, "225.0.0.250")
        c.transport.write("hello world", ("225.0.0.250", portno))
        d = defer.Deferred()
        reactor.callLater(0.4, d.callback, None, c, c2, p, p2)
        return d 
Example #7
Source File: test_udp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testMulticast(self):
        c = Server()
        p = reactor.listenMulticast(0, c)
        self.runUntilSuccess(self.server.transport.joinGroup, "225.0.0.250")
        c.transport.write("hello world",
                          ("225.0.0.250",
                           self.server.transport.getHost().port))

        iters = 0
        while iters < 100 and len(self.server.packets) == 0:
            reactor.iterate(0.05);
            iters += 1
        self.assertEquals(self.server.packets[0][0], "hello world")
        p.stopListening() 
Example #8
Source File: test_udp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.server = Server()
        self.client = Client()
        # multicast won't work if we listen over loopback, apparently
        self.port1 = reactor.listenMulticast(0, self.server)
        self.port2 = reactor.listenMulticast(0, self.client)
        reactor.iterate()
        reactor.iterate()
        self.client.transport.connect("127.0.0.1",
                                      self.server.transport.getHost().port) 
Example #9
Source File: test_udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_multiListen(self):
        """
        Test that multiple sockets can listen on the same multicast port and
        that they both receive multicast messages directed to that address.
        """
        firstClient = Server()
        firstPort = reactor.listenMulticast(
            0, firstClient, listenMultiple=True)

        portno = firstPort.getHost().port

        secondClient = Server()
        secondPort = reactor.listenMulticast(
            portno, secondClient, listenMultiple=True)

        joined = self.server.transport.joinGroup("225.0.0.250")

        def serverJoined(ignored):
            d1 = firstClient.packetReceived = Deferred()
            d2 = secondClient.packetReceived = Deferred()
            firstClient.transport.write("hello world", ("225.0.0.250", portno))
            return gatherResults([d1, d2])
        joined.addCallback(serverJoined)

        def gotPackets(ignored):
            self.assertEquals(firstClient.packets[0][0], "hello world")
            self.assertEquals(secondClient.packets[0][0], "hello world")
        joined.addCallback(gotPackets)

        def cleanup(passthrough):
            result = gatherResults([
                maybeDeferred(firstPort.stopListening),
                maybeDeferred(secondPort.stopListening)])
            result.addCallback(lambda ign: passthrough)
            return result
        joined.addBoth(cleanup)
        return joined 
Example #10
Source File: test_udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_multicast(self):
        """
        Test that a multicast group can be joined and messages sent to and
        received from it.
        """
        c = Server()
        p = reactor.listenMulticast(0, c)
        addr = self.server.transport.getHost()

        joined = self.server.transport.joinGroup("225.0.0.250")

        def cbJoined(ignored):
            d = self.server.packetReceived = Deferred()
            c.transport.write("hello world", ("225.0.0.250", addr.port))
            return d
        joined.addCallback(cbJoined)

        def cbPacket(ignored):
            self.assertEquals(self.server.packets[0][0], "hello world")
        joined.addCallback(cbPacket)

        def cleanup(passthrough):
            result = maybeDeferred(p.stopListening)
            result.addCallback(lambda ign: passthrough)
            return result
        joined.addCallback(cleanup)

        return joined 
Example #11
Source File: test_udp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.server = Server()
        self.client = Client()
        # multicast won't work if we listen over loopback, apparently
        self.port1 = reactor.listenMulticast(0, self.server)
        self.port2 = reactor.listenMulticast(0, self.client)
        self.client.transport.connect(
            "127.0.0.1", self.server.transport.getHost().port) 
Example #12
Source File: main.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def main():
    p = argparse.ArgumentParser(description='Paradrop daemon running on client')
    p.add_argument('--mode', '-m', help='Set the mode to one of [production, local, unittest]',
                   action='store', type=str, default='production')
    p.add_argument('--portal', '-p', help='Set the folder of files for local portal',
                   action='store', type=str)
    p.add_argument('--no-exec', help='Skip execution of configuration commands',
                   action='store_false', dest='execute')

    args = p.parse_args()
    # print args

    settings.loadSettings(args.mode, [])

    update_manager = UpdateManager(reactor)
    update_fetcher = UpdateFetcher(update_manager)
    WampSession.set_update_fetcher(update_fetcher)
    ProcessMonitor.allowedActions = set()

    # Start the configuration service as a thread
    confd.main.run_thread(execute=args.execute)

    airshark_manager = AirsharkManager()

    # Globally assign the nexus object so anyone else can access it.
    nexus.core = Nexus(update_fetcher, update_manager)
    http_server = HttpServer(update_manager, update_fetcher, airshark_manager, args.portal)
    setup_http_server(http_server, '0.0.0.0', settings.PORTAL_SERVER_PORT)
    reactor.listenMulticast(1900, SsdpResponder(), listenMultiple=True)

    reactor.run() 
Example #13
Source File: upnp.py    From p2pool-n with GNU General Public License v3.0 5 votes vote down vote up
def search_device(self):
        """
        Triggers a UPnP device discovery.
        
        The returned deferred will be called with the L{UPnPDevice} that has
        been found in the LAN.
        
        @return: A deferred called with the detected L{UPnPDevice} instance.
        @rtype: L{twisted.internet.defer.Deferred}
        """
        if self._discovery is not None:
            raise ValueError('already used')
        self._discovery = defer.Deferred()
        self._discovery_timeout = reactor.callLater(6, self._on_discovery_timeout)
        
        attempt = 0
        mcast = None
        while True:
            try:
                self.mcast = reactor.listenMulticast(1900+attempt, self)
                break
            except CannotListenError:
                attempt = random.randint(0, 500)
        
        # joined multicast group, starting upnp search
        self.mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)
        
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        self.transport.write(_UPNP_SEARCH_REQUEST, (_UPNP_MCAST, _UPNP_PORT))
        
        return self._discovery
    
    #Private methods 
Example #14
Source File: ipdiscover.py    From p2pool-n with GNU General Public License v3.0 5 votes vote down vote up
def _discover_multicast():
    """
    Local IP discovery protocol via multicast:
        - Broadcast 3 ping multicast packet with "ping" in it
        - Wait for an answer
        - Retrieve the ip address from the returning packet, which is ours
    """
    
    nonce = str(random.randrange(2**64))
    p = _LocalNetworkMulticast(nonce)
    
    for attempt in itertools.count():
        port = 11000 + random.randint(0, 5000)
        try:
            mcast = reactor.listenMulticast(port, p)
        except CannotListenError:
            if attempt >= 10:
                raise
            continue
        else:
            break
    
    try:
        yield mcast.joinGroup('239.255.255.250', socket.INADDR_ANY)
        
        logging.debug("Sending multicast ping")
        for i in xrange(3):
            p.transport.write(nonce, ('239.255.255.250', port))
        
        address, = yield p.address_received.get_deferred(5)
    finally:
        mcast.stopListening()
    
    defer.returnValue(address) 
Example #15
Source File: beacon.py    From iWant with MIT License 5 votes vote down vote up
def logout(self):
        # Announce dead with your uuid and the latest election id
        self.log.msg('Announce dead with your uuid and the latest election id')
        self._dead()
        print 'shutting down ... its been an honour serving you!'


# if __name__ == '__main__':
#    import random,os,sys
#    try:
#        from netifaces import interfaces, ifaddresses, AF_INET
#
#        def ip4_addresses():
#            ip_list = []
#            for interface in interfaces():
#                try:
#                    for link in ifaddresses(interface)[AF_INET]:
#                        ip_list.append(link['addr'])
#                except:
#                    pass
#            return ip_list
#        ips = ip4_addresses()
#        # print ips
#        ip = input('Enter index of ip addr:')
#        timeuuid = time_uuid.TimeUUID.with_utcnow()
#        book = CommonlogBook(identity=timeuuid, state=0, ip = ips[ip-1])
#        reactor.listenMulticast(MCAST_ADDR[1], CommonroomProtocol(book), listenMultiple=True)
#        reactor.run()
#    except KeyboardInterrupt:
#        reactor.stop()
#        try:
#            sys.exit(0)
#        except SystemExit:
#            os._exit(0) 
Example #16
Source File: test_udp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_multiListen(self):
        """
        Test that multiple sockets can listen on the same multicast port and
        that they both receive multicast messages directed to that address.
        """
        firstClient = Server()
        firstPort = reactor.listenMulticast(
            0, firstClient, listenMultiple=True)

        portno = firstPort.getHost().port

        secondClient = Server()
        secondPort = reactor.listenMulticast(
            portno, secondClient, listenMultiple=True)

        theGroup = "225.0.0.250"
        joined = gatherResults([self.server.transport.joinGroup(theGroup),
                                firstPort.joinGroup(theGroup),
                                secondPort.joinGroup(theGroup)])


        def serverJoined(ignored):
            d1 = firstClient.packetReceived = Deferred()
            d2 = secondClient.packetReceived = Deferred()
            firstClient.transport.write(b"hello world", (theGroup, portno))
            return gatherResults([d1, d2])
        joined.addCallback(serverJoined)

        def gotPackets(ignored):
            self.assertEqual(firstClient.packets[0][0], b"hello world")
            self.assertEqual(secondClient.packets[0][0], b"hello world")
        joined.addCallback(gotPackets)

        def cleanup(passthrough):
            result = gatherResults([
                maybeDeferred(firstPort.stopListening),
                maybeDeferred(secondPort.stopListening)])
            result.addCallback(lambda ign: passthrough)
            return result
        joined.addBoth(cleanup)
        return joined 
Example #17
Source File: test_udp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_multicast(self):
        """
        Test that a multicast group can be joined and messages sent to and
        received from it.
        """
        c = Server()
        p = reactor.listenMulticast(0, c)
        addr = self.server.transport.getHost()

        joined = self.server.transport.joinGroup("225.0.0.250")

        def cbJoined(ignored):
            d = self.server.packetReceived = Deferred()
            c.transport.write(b"hello world", ("225.0.0.250", addr.port))
            return d
        joined.addCallback(cbJoined)

        def cbPacket(ignored):
            self.assertEqual(self.server.packets[0][0], b"hello world")
        joined.addCallback(cbPacket)

        def cleanup(passthrough):
            result = maybeDeferred(p.stopListening)
            result.addCallback(lambda ign: passthrough)
            return result
        joined.addCallback(cleanup)

        return joined 
Example #18
Source File: test_udp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def setUp(self):
        self.server = Server()
        self.client = Client()
        # multicast won't work if we listen over loopback, apparently
        self.port1 = reactor.listenMulticast(0, self.server)
        self.port2 = reactor.listenMulticast(0, self.client)
        self.client.transport.connect(
            "127.0.0.1", self.server.transport.getHost().port) 
Example #19
Source File: test_udp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_multiListen(self):
        """
        Test that multiple sockets can listen on the same multicast port and
        that they both receive multicast messages directed to that address.
        """
        firstClient = Server()
        firstPort = reactor.listenMulticast(
            0, firstClient, listenMultiple=True)

        portno = firstPort.getHost().port

        secondClient = Server()
        secondPort = reactor.listenMulticast(
            portno, secondClient, listenMultiple=True)

        theGroup = "225.0.0.250"
        joined = gatherResults([self.server.transport.joinGroup(theGroup),
                                firstPort.joinGroup(theGroup),
                                secondPort.joinGroup(theGroup)])


        def serverJoined(ignored):
            d1 = firstClient.packetReceived = Deferred()
            d2 = secondClient.packetReceived = Deferred()
            firstClient.transport.write(b"hello world", (theGroup, portno))
            return gatherResults([d1, d2])
        joined.addCallback(serverJoined)

        def gotPackets(ignored):
            self.assertEqual(firstClient.packets[0][0], b"hello world")
            self.assertEqual(secondClient.packets[0][0], b"hello world")
        joined.addCallback(gotPackets)

        def cleanup(passthrough):
            result = gatherResults([
                maybeDeferred(firstPort.stopListening),
                maybeDeferred(secondPort.stopListening)])
            result.addCallback(lambda ign: passthrough)
            return result
        joined.addBoth(cleanup)
        return joined 
Example #20
Source File: test_udp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_multicast(self):
        """
        Test that a multicast group can be joined and messages sent to and
        received from it.
        """
        c = Server()
        p = reactor.listenMulticast(0, c)
        addr = self.server.transport.getHost()

        joined = self.server.transport.joinGroup("225.0.0.250")

        def cbJoined(ignored):
            d = self.server.packetReceived = Deferred()
            c.transport.write(b"hello world", ("225.0.0.250", addr.port))
            return d
        joined.addCallback(cbJoined)

        def cbPacket(ignored):
            self.assertEqual(self.server.packets[0][0], b"hello world")
        joined.addCallback(cbPacket)

        def cleanup(passthrough):
            result = maybeDeferred(p.stopListening)
            result.addCallback(lambda ign: passthrough)
            return result
        joined.addCallback(cleanup)

        return joined 
Example #21
Source File: test_udp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.server = Server()
        self.client = Client()
        # multicast won't work if we listen over loopback, apparently
        self.port1 = reactor.listenMulticast(0, self.server)
        self.port2 = reactor.listenMulticast(0, self.client)
        self.client.transport.connect(
            "127.0.0.1", self.server.transport.getHost().port)