When doing a network broadcast from Python, I get this: OSError: [Errno 101] Network is unreachable

My code is as follows:

def send(ip, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, 4601))
        response = sock.recv(1024)
    if response:
        return response
        return False

I replaced ip with "<broadcast>" and that's when I get the error. My server is listening on port 4601 so I don't understand what's going on. I also replaced it with the actual network broadcast address provided in network-manager and still got nothing.


In case of broadcast, you should not use TCP rather you should use UDP. Then again you need to use sendto() method instead of connect(). sendto() is used to send data to a certain address which is the "broadcast" address in our case. So the following should work:

import socket
message = "Hello"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(message, ('<broadcast>', 50000))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.