0

How may I create a socket that can both send and receive UDP packets?

My application requires that sockets are bound to the physical network interface because it's a multicast system with multiple interfaces connecting to redundant, duplicate networks on the target device. It is necessary that my script be able to distinctly communicate with each network without interaction with the other networks. This is why binding to the interface is necessary.

Here is what I have so far, but it keeps timing out. What am I doing wrong?

import socket

s = socket.socket(socket.AF_PACKET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setblocking(True)
s.settimeout(3.0)
s.bind(('eth0', 0))

z_data, z_addr = s.recvfrom(1024)  # expected target frame total length is 264 bytes

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.timeout: timed out
3
  • 1
    Have you tried using AF_INET/6 instead of AF_PACKET? Commented Nov 16, 2023 at 18:13
  • My understanding from the documentation is that AF_INET requires (host_ip, port) for binding. Only AF_PACKET seems to allow binding with the interface name. Commented Nov 16, 2023 at 20:52
  • An AF_INET/6 socket can be bound to an interface name via SO_BINDTODEVICE: stackoverflow.com/questions/7221577 Commented Nov 16, 2023 at 21:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.