1
broadcaster = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
broadcaster.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
broadcaster.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

def send_broadcast_thread():
    msg = "test"
    while True:
        # TODO: write logic for sending broadcasts.
        broadcaster.sendto(msg.encode(), ('255.255.255.255', get_broadcast_port()))
        print(msg.encode())
        time.sleep(1)

def receive_broadcast_thread():
    broadcaster.bind(('', get_broadcast_port()))
    while True:
        data, (ip, port) = broadcaster.recvfrom(4096)
        print(f"RECV: {data} FROM: T{ip}:{port}")

I get this error when I try to run this code. I call each function of them in a separate daemon thread.

line 88, in receive_broadcast_thread
    broadcaster.bind(('', get_broadcast_port())) OSError: [Errno 22] Invalid argument
Sam Mason
  • 15,216
  • 1
  • 41
  • 60
Ahmed Refaat
  • 103
  • 1
  • 3
  • 11

2 Answers2

0

From the looks of it, you're providing an invalid hostname (empty string) on the second line of your receive_broadcast_thread() function.

linqo
  • 617
  • 4
  • 16
0

AFAICT, you can bind a socket at most once. For example, the Linux man pages say:

EINVAL The socket is already bound to an address.

the EINVAL error number is defined as:

#define EINVAL          22      /* Invalid argument */

which seems to match up with what you're getting.

To fix your problem, I'd try moving the bind out of receive_broadcast_thread to just after where you set all the socket options

Sam Mason
  • 15,216
  • 1
  • 41
  • 60
  • Thank you for your comment. This does solve the error but when I try running the code from two terminals at once it prints the same port number in both of them ( in the receive_broadcast function) But it should print two port numbers because they should act as two separate devices, right? – Ahmed Refaat May 01 '20 at 22:41
  • that would depend on what `get_broadcast_port` is doing. you're setting `SO_REUSEADDR` so you're allowing multiple programs to be bound to that UDP port. maybe post another question that includes the relevant details? – Sam Mason May 01 '20 at 23:07