如何使用localhost上的多播限制流量 [英] How to limit traffic using multicast over localhost

查看:91
本文介绍了如何使用localhost上的多播限制流量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在本地主机上使用多播UDP来实现在一台机器上运行的协作程序的松散集合.以下代码可在Mac OSX,Windows和linux上正常运行.缺陷在于该代码还将在本地网络之外接收UDP数据包.例如,当sendSock.sendto(pkt, ('192.168.0.25', 1600))从我的网络上的另一个邮箱发送时,被我的测试机接收.

I'm using multicast UDP over localhost to implement a loose collection of cooperative programs running on a single machine. The following code works well on Mac OSX, Windows and linux. The flaw is that the code will receive UDP packets outside of the localhost network as well. For example, sendSock.sendto(pkt, ('192.168.0.25', 1600)) is received by my test machine when sent from another box on my network.

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网络的多播数据包,还是我需要测试每个接收到的数据包的地址?

I've attempted to recvSock.bind(("127.0.0.1", addr[1])), but that prevents the socket from receiving any multicast traffic. Is there a proper way to configure recvSock to only accept multicast packets from the 127/24 network, or do I need to test the address of each received packet?

推荐答案

不幸的是,多播IP没有任何此类按子网过滤"功能-因此,除非您想破坏IPTables(在Linux上)或同等功能系统/网络的防火墙" SW/HW尝试并丢弃"您不喜欢的每个多播数据包,我认为您必须在应用程序级别执行(在fromAddr中进行测试例如,您的内部循环).来自其他主机的IP流量会大大降低性能吗??

Unfortunately, multicast IP doesn't have any such "filtering by subnetwork" feature -- so, unless you want to muck with IPTables (on Linux) or equivalent "firewall" SW/HW of your system/network to try and "drop on the floor" every multicast packet you don't like, I think you'll have to do it at application level (with a test on fromAddr in your inner loop, for example). Is the IP traffic from other hosts so much it degrades your performance...?

这篇关于如何使用localhost上的多播限制流量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆