There is a server that will be sending messages to a multicast group.
I have multiple clients that will be receiving messages from that multicast group.
It's my understanding that anyone can send messages to the multicast group if they're subscribed on the socket. This means that subscribing would open me up to a lot of traffic that I don't care about.
In my client code, I could setup a conditional to check if the messages comes from the sender I want to listen to:
data, address = sock.recvfrom(1024)
if address not in trusted:
continue
However, I was wondering if there was a way to configure the socket to only see the traffic of trusted hosts.
Even further, I'd like to know if there's a way to filter by source address when subscribing to the multicast group from the python client code.
If not, would I just need to configure the router to filter multicast traffic by the source IP?
What options are available here?
You can do the filtering by using source specific multicast, which allows a socket to receive multicast traffic only from certain senders.
Typically you would join a multicast group like this with the IP_ADD_MEMBERSHIP
socket option:
MCAST_GRP = '224.1.1.1'
LOCAL_INT_IP = '192.168.1.2' # local address of joining interface
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP),
socket.inet_aton(LOCAL_INT_IP))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
Instead, use the IP_ADD_SOURCE_MEMBERSHIP
option, which allows you to specify a sender IP:
MCAST_GRP = '232.1.1.1'
LOCAL_INT_IP = '192.168.1.2' # local address of joining interface
SENDER_IP = '192.168.1.10'
mreq_src = struct.pack("4sl", socket.inet_aton(MCAST_GRP),
socket.inet_aton(LOCAL_INT_IP), socket.inet_aton(SENDER_IP))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_SOURCE_MEMBERSHIP, mreq_src)
One important thing to note about source specific multicast is that the multicast address must be in the 232.0.0.0/8 range.