Home > Back-end >  Python 2.7 socket.sendto multicast message not leaving the machine
Python 2.7 socket.sendto multicast message not leaving the machine

Time:08-31

I am writing a python 2.7 program to discover specific devices via mDNS. I'm only able to use standard modules. Because of that, I have to implement the discovery using the socket module only.

My current implementation, given below, does not result in a telegram recorded by Wireshark. So, it seems no message is leaving my machine.

No error message is printed out.

My current implementation is:

# configure socket
mcast_port = 5353
mcast_grp = ('224.0.0.251', mcast_port)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.settimeout(5)

ttl = struct.pack('b', 5)
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, ttl)
sock.setsockopt(socket.SOL_IP, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)

try:
  bytes_send = sock.sendto(query_msg, mcast_grp)
    if bytes_send != len(query_msg):
      print("Something wrong here")
except socket.error as e:
  self.log_data("Socket Error", "discover: "   str(e))
  sock.shutdown(socket.SHUT_RDWR)
  sock.close()
except Exception as e:
  self.log_data("Error", "discover: "   str(e))
  sock.shutdown(socket.SHUT_RDWR)
  sock.close()

Anyone sees, what I'm not seeing?

CodePudding user response:

As suggested in the comments of the ticket linked by @Keith, a local host interface might be chosen to send the request. This was the problem in my case. Forcing the socket to use the correct interface was the solution:

sock.bind(("192.168.0.123", 5354))

While "192.168.0.123" was the IP address of the interface.

  • Related