Guido van Rossum | 4fab6a5 | 1992-09-08 21:19:55 +0000 | [diff] [blame] | 1 | # Send/receive UDP multicast packets (SGI) |
| 2 | # After /usr/people/4Dgifts/examples/network/mcast.c |
| 3 | # Usage: |
| 4 | # mcast -s (sender) |
Guido van Rossum | c8833d4 | 1992-09-24 10:33:16 +0000 | [diff] [blame^] | 5 | # mcast -b (sender, using broadcast instead multicast) |
Guido van Rossum | 4fab6a5 | 1992-09-08 21:19:55 +0000 | [diff] [blame] | 6 | # mcast (receivers) |
| 7 | |
| 8 | MYPORT = 8123 |
| 9 | MYGROUP_BYTES = 225, 0, 0, 250 |
| 10 | |
| 11 | import sys |
| 12 | import time |
| 13 | import struct |
| 14 | from socket import * |
| 15 | from SOCKET import * |
| 16 | from IN import * |
| 17 | |
Guido van Rossum | c8833d4 | 1992-09-24 10:33:16 +0000 | [diff] [blame^] | 18 | sender = sys.argv[1:] |
Guido van Rossum | 4fab6a5 | 1992-09-08 21:19:55 +0000 | [diff] [blame] | 19 | |
| 20 | s = socket(AF_INET, SOCK_DGRAM) |
| 21 | |
| 22 | if sender: |
Guido van Rossum | c8833d4 | 1992-09-24 10:33:16 +0000 | [diff] [blame^] | 23 | if sys.argv[1] == '-b': |
| 24 | s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) |
| 25 | mygroup = '<broadcast>' |
| 26 | else: |
| 27 | # Ugly: construct decimal IP address string from MYGROUP_BYTES |
| 28 | mygroup = '' |
| 29 | for byte in MYGROUP_BYTES: mygroup = mygroup + '.' + `byte` |
| 30 | mygroup = mygroup[1:] |
| 31 | ttl = struct.pack('b', 1) # Time-to-live |
| 32 | s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl) |
Guido van Rossum | 4fab6a5 | 1992-09-08 21:19:55 +0000 | [diff] [blame] | 33 | while 1: |
Guido van Rossum | c8833d4 | 1992-09-24 10:33:16 +0000 | [diff] [blame^] | 34 | data = `time.time()` |
| 35 | ## data = data + (1400 - len(data)) * '\0' |
Guido van Rossum | 4fab6a5 | 1992-09-08 21:19:55 +0000 | [diff] [blame] | 36 | s.sendto(data, (mygroup, MYPORT)) |
Guido van Rossum | c8833d4 | 1992-09-24 10:33:16 +0000 | [diff] [blame^] | 37 | time.sleep(1) |
Guido van Rossum | 4fab6a5 | 1992-09-08 21:19:55 +0000 | [diff] [blame] | 38 | else: |
| 39 | # Bind the socket to my port |
| 40 | s.bind('', MYPORT) |
| 41 | |
| 42 | # Allow multiple copies of this program on one machine |
| 43 | s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) # (Not strictly needed) |
| 44 | |
| 45 | # Ugly: construct binary group address from MYGROUP_BYTES |
| 46 | grpaddr = 0 |
| 47 | for byte in MYGROUP_BYTES: grpaddr = (grpaddr << 8) | byte |
| 48 | |
| 49 | # Construct struct mreq from grpaddr and ifaddr |
| 50 | ifaddr = INADDR_ANY |
| 51 | mreq = struct.pack('ll', grpaddr, ifaddr) |
| 52 | |
| 53 | # Add group membership |
| 54 | s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) |
| 55 | |
| 56 | # Loop, printing any data we receive |
| 57 | while 1: |
| 58 | data, sender = s.recvfrom(1500) |
| 59 | while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's |
| 60 | print sender, ':', `data` |