Using python, network programming is very simple.
There are several networking library already available, so you can think to use one of this library to do the work.
My favourite libraries are the following:
- Twisted
- Pyro
- py-multicast 1.4
Anyway, since multicast traffic is no different than regular UDP except for the IP address. We are going to take a look at the standard socket library.
It is simple to use.
The sender program will open a new datagram socket and then it will configure the socket to use multicast with a time to live of 32 hops (line 7).
At line 8 the program will send the "Hello World" Message to the multicast group
import socket MCAST_GRP = 224.0.0.1 MCAST_PORT = 10000 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) sock.sendto("Hello World", (MCAST_GRP, MCAST_PORT))
The receiver program will create a new datagram socket then it will bind the socket to the Multicast group and port, last it will loop forever waiting from multicast data on that socket. Any received string will be printed out. (lines 14-15)
import socket import struct MCAST_GRP = 224.0.0.1 MCAST_PORT = 10000 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((MCAST_GRP, MCAST_PORT)) mreq = struct.pack("4s", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) while True: print sock.recv(1024)
Gg1
I’m sorry if I’m doing something wrong but this code is not printing anything.
I created to files receiver.py and sender.py and ran both files.
mreq = struct.pack(“4sl”, socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)