Is there a way to distinguish unicast and multicast when receiving UDP datagram from same socket?

  multicast, python, sockets, udp

I have an application that meeds to:

  • talks in UDP
  • support optionally disabling multicast.
  • treat multicast message the same way as unicast message but with few restrictions

I thought I should use same UDP socket to receive both unicast and multicast datagrams.

# Python version used: 3.9.1
import socket
import struct

host = ""
# host = ""
listen_all = True
port = 5683

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if listen_all:
    s.bind(("", port))
    s.bind((host, port))
mreq = struct.pack("4sl", socket.inet_aton(host), socket.INADDR_ANY)
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

data = None
while True:
    # data, addr = s.recvfrom(1024)
    data, ancdata, msg_flags, addr = s.recvmsg(1024)
    print(addr, ":", data, ancdata, msg_flags)


import socket

dest = ""
dest = ""
port = 5683

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.sendto("Hello world".encode(), (dest, port))

I soon noticed I need a way to distinguish multicast datagram from unicast datagram. But I was unable to find a solution nor related question on how to achieve this on the internet.

Hence the question: When receiving UDP datagram from same socket, is there a way to tell whether datagram is unicast or multicast?

Source: Python Questions