1 # Send/receive UDP multicast packets.
2 # Requires that your OS kernel supports IP multicast.
3 # This is built-in on SGI, still optional for most other vendors.
7 # mcast -b (sender, using broadcast instead multicast)
11 MYGROUP
= '225.0.0.250'
29 # Sender subroutine (only one per local area network)
31 s
= socket(AF_INET
, SOCK_DGRAM
)
33 s
.setsockopt(SOL_SOCKET
, SO_BROADCAST
, 1)
34 mygroup
= '<broadcast>'
37 ttl
= struct
.pack('b', 1) # Time-to-live
38 s
.setsockopt(IPPROTO_IP
, IP_MULTICAST_TTL
, ttl
)
40 data
= repr(time
.time())
41 ## data = data + (1400 - len(data)) * '\0'
42 s
.sendto(data
, (mygroup
, MYPORT
))
46 # Receiver subroutine (as many as you like)
48 # Open and initialize the socket
49 s
= openmcastsock(MYGROUP
, MYPORT
)
51 # Loop, printing any data we receive
53 data
, sender
= s
.recvfrom(1500)
54 while data
[-1:] == '\0': data
= data
[:-1] # Strip trailing \0's
55 print sender
, ':', repr(data
)
58 # Open a UDP socket, bind it to a port and select a multicast group
59 def openmcastsock(group
, port
):
60 # Import modules used only here
65 s
= socket(AF_INET
, SOCK_DGRAM
)
67 # Allow multiple copies of this program on one machine
68 # (not strictly needed)
69 s
.setsockopt(SOL_SOCKET
, SO_REUSEADDR
, 1)
74 # Look up multicast group address in name server
75 # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
76 group
= gethostbyname(group
)
78 # Construct binary group address
79 bytes
= map(int, string
.split(group
, "."))
81 for byte
in bytes
: grpaddr
= (grpaddr
<< 8) | byte
83 # Construct struct mreq from grpaddr and ifaddr
85 mreq
= struct
.pack('ll', htonl(grpaddr
), htonl(ifaddr
))
87 # Add group membership
88 s
.setsockopt(IPPROTO_IP
, IP_ADD_MEMBERSHIP
, mreq
)