UDP socket sendto() functions

dgrat picture dgrat · May 15, 2015 · Viewed 11.4k times · Source

I get an error if I want to write on my udp socket like this. According to the docu there shouldn't be a problem. I don't understand why bind() works well in the same way but sendto() fails.

udp_port = 14550
udp_server  = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_server.bind(('127.0.0.1', udp_port))
udp_clients = {}

Error:

udp_server.sendto('', ('192.0.0.1', 14550) )
socket.error: [Errno 22] Invalid argument

Answer

Serge Ballesta picture Serge Ballesta · May 15, 2015

The error says that you have an invalid argument. When reading your code, I can say that the offending argument is the IP address :

  • you bind your socket to 127.0.0.1
  • you try to send data to 192.0.0.1 that is on another network

If you want to send data to a host at IP address 192.0.0.1, bind the socket to a local network interface on same network, or on a network that can find a route to 192.0.0.1

I have a (private) local network at 192.168.56.*, if I bind the socket to 192.168.56.x (x being local address), I can send data to 192.168.56.y (y being the address of the server) ; but if I bind to 127.0.0.1 I get the IllegalArgumentException.