OSError: [Errno 101] Network is unreachable

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)) try: sock.sendall(message) response = sock.recv(1024) finally: sock.close() if response: return response else: 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.

1 Answer

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like