-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudpsend.py
40 lines (32 loc) · 1.02 KB
/
udpsend.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import socket
import struct
import sys
message = 'very important data'
multicast_group = ('224.3.29.71', 10000)
# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set a timeout so the socket does not block indefinitely when trying
# to receive data.
sock.settimeout(2)
# Set the time-to-live for messages to 1 so they do not go past the
# local network segment.
ttl = struct.pack('b', 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
try:
# Send data to the multicast group
print( 'sending "%s"' % message)
message=message.encode("utf-8")
sent = sock.sendto(message, multicast_group)
# Look for responses from all recipients
while True:
print( 'waiting to receive')
try:
data, server = sock.recvfrom(16)
except socket.timeout:
print( 'timed out, no more responses')
break
else:
print( 'received "%s" from %s' % (data, server))
finally:
print( 'closing socket')
sock.close()