Forgot the code... doh! :)

#! /usr/bin/env python

import socket
import time

class MulticastSender(object):
        def __init__(self, MCAST_ADDR = "224.168.2.9", MCAST_PORT = 1600):
                self.MCAST_ADDR = MCAST_ADDR
                self.MCAST_PORT = MCAST_PORT
                ANY = "0.0.0.0"
                SENDERPORT=1501
#create a UDP socket
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
#allow multiple sockets to use the same PORT number
                self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#The sender is bound on (0.0.0.0:1501)
                self.sock.bind((ANY,SENDERPORT))
#Tell the kernel that we want to multicast and that the data is sent
#to everyone (255 is the level of multicasting)
                self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL,
255)

        def send(self, data):
                self.sock.sendto(data, (self.MCAST_ADDR, self.MCAST_PORT));

class MulticastReceiver(object):
        def __init__(self, MCAST_ADDR = "224.168.2.9", MCAST_PORT = 1600):
                ANY = "0.0.0.0"
#create a UDP socket
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
#allow multiple sockets to use the same PORT number
                self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#Bind to the port that we know will receive multicast data
                self.sock.bind((ANY,MCAST_PORT))
#tell the kernel that we are a multicast socket
                self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL,
255)
#Tell the kernel that we want to add ourselves to a multicast group
#The address for the multicast group is the third param
                status = self.sock.setsockopt(socket.IPPROTO_IP,
socket.IP_ADD_MEMBERSHIP, socket.inet_aton(MCAST_ADDR) +
socket.inet_aton(ANY));
                self.sock.setblocking(0)

        def setblocking(self, flag):
                self.sock.setblocking(flag)

        def recv(self, size = 1024):
                return self.sock.recvfrom(size)

class Multicast(object):
        def __init__(self):
                self.__ms = MulticastSender()
                self.__mr = MulticastReceiver()

        def send(self, data):
                self.__ms.send(data)

        def recv(self, size = 1024):
                return self.__mr.recv()

if __name__ == "__main__":
        mc = Multicast()
        while 1:
                try:
                        data, addr = mc.recv()
                except socket.error, e:
                        #print "sock.error: ", e
                        pass
                else:
                        print "FROM: ", addr
                        print "DATA: ", data
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to