PageRenderTime 27ms CodeModel.GetById 21ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/Demo/sockets/mcast.py

http://unladen-swallow.googlecode.com/
Python | 93 lines | 49 code | 12 blank | 32 comment | 9 complexity | 3c013f146fef1548e876ea55ec72e2c9 MD5 | raw file
 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.
 4#
 5# Usage:
 6#   mcast -s (sender)
 7#   mcast -b (sender, using broadcast instead multicast)
 8#   mcast    (receivers)
 9
10MYPORT = 8123
11MYGROUP = '225.0.0.250'
12
13import sys
14import time
15import struct
16from socket import *
17
18
19# Main program
20def main():
21    flags = sys.argv[1:]
22    #
23    if flags:
24        sender(flags[0])
25    else:
26        receiver()
27
28
29# Sender subroutine (only one per local area network)
30def sender(flag):
31    s = socket(AF_INET, SOCK_DGRAM)
32    if flag == '-b':
33        s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
34        mygroup = '<broadcast>'
35    else:
36        mygroup = MYGROUP
37        ttl = struct.pack('b', 1)               # Time-to-live
38        s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
39    while 1:
40        data = repr(time.time())
41##              data = data + (1400 - len(data)) * '\0'
42        s.sendto(data, (mygroup, MYPORT))
43        time.sleep(1)
44
45
46# Receiver subroutine (as many as you like)
47def receiver():
48    # Open and initialize the socket
49    s = openmcastsock(MYGROUP, MYPORT)
50    #
51    # Loop, printing any data we receive
52    while 1:
53        data, sender = s.recvfrom(1500)
54        while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
55        print sender, ':', repr(data)
56
57
58# Open a UDP socket, bind it to a port and select a multicast group
59def openmcastsock(group, port):
60    # Import modules used only here
61    import string
62    import struct
63    #
64    # Create a socket
65    s = socket(AF_INET, SOCK_DGRAM)
66    #
67    # Allow multiple copies of this program on one machine
68    # (not strictly needed)
69    s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
70    #
71    # Bind it to the port
72    s.bind(('', port))
73    #
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)
77    #
78    # Construct binary group address
79    bytes = map(int, string.split(group, "."))
80    grpaddr = 0
81    for byte in bytes: grpaddr = (grpaddr << 8) | byte
82    #
83    # Construct struct mreq from grpaddr and ifaddr
84    ifaddr = INADDR_ANY
85    mreq = struct.pack('ll', htonl(grpaddr), htonl(ifaddr))
86    #
87    # Add group membership
88    s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
89    #
90    return s
91
92
93main()