如何在Python中发送和接收UDP多播?有标准库吗?
这对我有用:
接收
import socket import struct MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 IS_ALL_GROUPS = True sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if IS_ALL_GROUPS: # on this port, receives ALL multicast groups sock.bind(('', MCAST_PORT)) else: # on this port, listen ONLY to MCAST_GRP sock.bind((MCAST_GRP, MCAST_PORT)) mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) while True: print sock.recv(10240)
发送
import socket MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 # regarding socket.IP_MULTICAST_TTL # --------------------------------- # for all packets sent, after two hops on the network the packet will not # be re-sent/broadcast (see https://www.tldp.org/HOWTO/Multicast-HOWTO-6.html) MULTICAST_TTL = 2 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL) sock.sendto("robot", (MCAST_GRP, MCAST_PORT))
它基于http://wiki.python.org/moin/UdpCommunication中不起作用的示例.
我的系统是... Linux 2.6.31-15-generic#50-Ubuntu SMP Tue 11月10日14:54:29 UTC 2009 i686 GNU/Linux Python 2.6.4
广播到组播组的组播发送方:
#!/usr/bin/env python import socket import struct def main(): MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 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)) if __name__ == '__main__': main()
从多播组读取并将十六进制数据打印到控制台的多播接收器:
#!/usr/bin/env python import socket import binascii def main(): MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except AttributeError: pass sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) sock.bind((MCAST_GRP, MCAST_PORT)) host = socket.gethostbyname(socket.gethostname()) sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host)) sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(MCAST_GRP) + socket.inet_aton(host)) while 1: try: data, addr = sock.recvfrom(1024) except socket.error, e: print 'Expection' hexdata = binascii.hexlify(data) print 'Data = %s' % hexdata if __name__ == '__main__': main()
更好用:
sock.bind((MCAST_GRP, MCAST_PORT))
代替:
sock.bind(('', MCAST_PORT))
因为,如果要在同一端口上侦听多个多播组,您将获得所有侦听器上的所有消息.