summaryrefslogtreecommitdiffstats
path: root/Demo/sockets
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>1992-09-08 21:19:55 (GMT)
committerGuido van Rossum <guido@python.org>1992-09-08 21:19:55 (GMT)
commit4fab6a5b0bfd13a11833adde57b9c0ef97c9853c (patch)
treefc511a841303f878d51a02cb04af1e7bddcdfb72 /Demo/sockets
parent00c5ad6eeb7cf407c6233855c6621fc64af2d3d2 (diff)
downloadcpython-4fab6a5b0bfd13a11833adde57b9c0ef97c9853c.zip
cpython-4fab6a5b0bfd13a11833adde57b9c0ef97c9853c.tar.gz
cpython-4fab6a5b0bfd13a11833adde57b9c0ef97c9853c.tar.bz2
Initial revision
Diffstat (limited to 'Demo/sockets')
-rwxr-xr-xDemo/sockets/mcast.py54
1 files changed, 54 insertions, 0 deletions
diff --git a/Demo/sockets/mcast.py b/Demo/sockets/mcast.py
new file mode 100755
index 0000000..6dab50a
--- /dev/null
+++ b/Demo/sockets/mcast.py
@@ -0,0 +1,54 @@
+# Send/receive UDP multicast packets (SGI)
+# After /usr/people/4Dgifts/examples/network/mcast.c
+# Usage:
+# mcast -s (sender)
+# mcast (receivers)
+
+MYPORT = 8123
+MYGROUP_BYTES = 225, 0, 0, 250
+
+import sys
+import time
+import struct
+from socket import *
+from SOCKET import *
+from IN import *
+
+sender = (sys.argv[1:2] == ['-s'])
+
+s = socket(AF_INET, SOCK_DGRAM)
+
+if sender:
+ # Ugly: construct decimal IP address string from MYGROUP_BYTES
+ mygroup = ''
+ for byte in MYGROUP_BYTES: mygroup = mygroup + '.' + `byte`
+ mygroup = mygroup[1:]
+ ttl = struct.pack('b', 1) # Time-to-live
+ s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
+ while 1:
+ data = `time.time()` + '\n'
+ s.sendto(data, (mygroup, MYPORT))
+ time.sleep(5)
+else:
+ # Bind the socket to my port
+ s.bind('', MYPORT)
+
+ # Allow multiple copies of this program on one machine
+ s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) # (Not strictly needed)
+
+ # Ugly: construct binary group address from MYGROUP_BYTES
+ grpaddr = 0
+ for byte in MYGROUP_BYTES: grpaddr = (grpaddr << 8) | byte
+
+ # Construct struct mreq from grpaddr and ifaddr
+ ifaddr = INADDR_ANY
+ mreq = struct.pack('ll', grpaddr, ifaddr)
+
+ # Add group membership
+ s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
+
+ # Loop, printing any data we receive
+ while 1:
+ data, sender = s.recvfrom(1500)
+ while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
+ print sender, ':', `data`