UDP Communication
See also SoapOverUdp, TcpCommunication
Sending
Here's simple code to post a note by UDP in Python 3:
1 import socket
2
3 UDP_IP = "127.0.0.1"
4 UDP_PORT = 5005
5 MESSAGE = b"Hello, World!"
6
7 print("UDP target IP: %s" % UDP_IP)
8 print("UDP target port: %s" % UDP_PORT)
9 print("message: %s" % MESSAGE)
10
11 sock = socket.socket(socket.AF_INET, # Internet
12 socket.SOCK_DGRAM) # UDP
13 sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
Receiving
Here's simple code to receive UDP messages in Python 3:
Using UDP for e.g. File Transfers
If considering extending this example for e.g. file transfers, keep in mind that UDP is not reliable. So you'll have to handle packets getting lost and packets arriving out of order. In effect, to get something reliable you'll need to implement something similar to TCP on top of UDP, and you might want to consider using TCP instead.
That being said, sometimes you need to use UDP, e.g. for UDP hole punching. In that case, consider TFTP for python or UDT for python
Multicasting?
The official example of multicast can be found at /usr/share/doc/python2.3/examples/Demo/sockets/mcast.py (at least on Debian Sarge, after apt-get install python-examples). It worked on my machine, but I have yet to try it running on different machines. -- -- 200.138.245.121 2006-08-09 03:20:30
I've been googling for some time now, and still have yet to find a working example of Python multicast listening.
(The example below has been updated to work -- Steven Spencer 2005-04-14 13:19:00)
(I've replaced it with one that works. -- Asgeir S. Nilsen 2005-05-09 19:25:00)
(I've corrected the mreq according to the comment below -- Sebastian Setzer 2006-01-25 14:28:00)
(I added an "=" to the "4sl" struct packing. Both the old version and the new version work on my 32-bit machine, but the Python documentation for the struct module suggests that "l" would be 64 bits on an LP64 or LPI64 platform without it, so I thought it would be prudent to add. -- Kragen Sitaker 2010-04-28 07:03:00)
1 import socket
2 import struct
3
4 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
5 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
6 sock.bind(('', 4242))
7 # wrong: mreq = struct.pack("sl", socket.inet_aton("224.51.105.104"), socket.INADDR_ANY)
8 mreq = struct.pack("=4sl", socket.inet_aton("224.51.105.104"), socket.INADDR_ANY)
9
10 sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
11
12 while True:
13 print(sock.recv(10240))
The mreq packing is based on some code that I found, that does not work. On my computer, at least.
Sending to multicast groups is just fine; Here's some functional text:
(You might want to reconsider the IP_MULTICAST_TTL setting here -- the recommended value for local-network multicasts is < 32, whilst a value > 32 indicates multicasts which should traverse onto the Internet -- Asgeir S. Nilsen)
Note the above example is missing a bind() call. This will work OK if there is a multicast route setup in the IP routing table {i.e. os.system('route add 224.51.105.104 eth0')} But without a bind() nor route, the kernel will not determine which network interface to send the data on, and will return an error. There may be other ways for the "socket to network interface" mapping to be defined, but I forget what they are. (Chris David)
The above multicasting examples do not work on my computer, but I was able to fix them using code from http://sourceforge.net/projects/pyzeroconf. Try these examples:
1 # UDP multicast examples, Hugo Vincent, 2005-05-14.
2 import socket
3
4 def send(data, port=50000, addr='239.192.1.100'):
5 """send(data[, port[, addr]]) - multicasts a UDP datagram."""
6 # Create the socket
7 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
8 # Make the socket multicast-aware, and set TTL.
9 s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20) # Change TTL (=20) to suit
10 # Send the data
11 s.sendto(data, (addr, port))
12
13 def recv(port=50000, addr="239.192.1.100", buf_size=1024):
14 """recv([port[, addr[,buf_size]]]) - waits for a datagram and returns the data."""
15
16 # Create the socket
