How to get broadcast address with python socket in localhost?

Viewed 96

I try to send messages in localhost to broadcast address, but it does not work. When I use socket.INADDR_BROADCAST, I get [Errno 11001] getaddrinfo failed.

import socket


client_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_server.bind(("127.0.0.1", 12345))
client_server.connect((f"{socket.INADDR_BROADCAST}", 12345))

client_server.sendto("New user is connected".encode("utf-8"), (f"{socket.INADDR_BROADCAST}", 12345))
1 Answers

You are creating a TCP (SOCK_STREAM) socket. TCP has no notion of broadcasting. A TCP client socket cannot connect() to a broadcast IP, and a TCP server socket cannot listen() on a broadcast IP. That just makes no sense to do. The only way to broadcast a message in TCP is for the server to keep track of each client connected to it and then send the message to each client one at a time.

A UDP (SOCK_DGRAM) socket, on the other hand, can sendto() a message to a broadcast IP (if you enable the socket's SO_BROADCAST option beforehand), and it can recvfrom() a message that was sent to a broadcast IP belonging to the adapter that the socket is bound to.

Just note that bind()'ing a broadcasting UDP socket to 127.0.0.1 means that only UDP receivers also bound to 127.0.0.1 will be able to receive the broadcasts. You won't be able to broadcast over the network.

import socket

client_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#client_server.bind(("127.0.0.1", 12345))
client_server.setsockopt(client_server.SOL_SOCKET, client_server.SO_BROADCAST, 1)

client_server.sendto("New user is connected".encode("utf-8"), (f"{socket.INADDR_BROADCAST}", 12345))
Related