我在 localhost 上使用多播 UDP 来实现在单台机器上运行的协作程序的松散集合。以下代码在 Mac OSX、Windows 和 linux 上运行良好。缺陷是代码也会在 localhost 网络之外接收 UDP 数据包。例如,sendSock.sendto(pkt, ('192.168.0.25', 1600))
当从我的网络上的另一个盒子发送时,我的测试机器接收到。
import platform, time, socket, select
addr = ("239.255.2.9", 1600)
sendSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sendSock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 24)
sendSock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
socket.inet_aton("127.0.0.1"))
recvSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
recvSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
if hasattr(socket, 'SO_REUSEPORT'):
recvSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
recvSock.bind(("0.0.0.0", addr[1]))
status = recvSock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(addr[0]) + socket.inet_aton("127.0.0.1"));
while 1:
pkt = "Hello host: {1} time: {0}".format(time.ctime(), platform.node())
print "SEND to: {0} data: {1}".format(addr, pkt)
r = sendSock.sendto(pkt, addr)
while select.select([recvSock], [], [], 0)[0]:
data, fromAddr = recvSock.recvfrom(1024)
print "RECV from: {0} data: {1}".format(fromAddr, data)
time.sleep(2)
我尝试过recvSock.bind(("127.0.0.1", addr[1]))
,但这会阻止套接字接收任何多播流量。是否有适当的方法将 recvSock 配置为仅接受来自 127/24 网络的多播数据包,或者我是否需要测试每个接收到的数据包的地址?