4

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
dgrat
  • 2,214
  • 4
  • 24
  • 46

3 Answers3

9

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.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
3

Your bind call should not be binding to the loopback address. Try doing this:

udp_server.bind(('0.0.0.0', udp_port))
steve
  • 2,488
  • 5
  • 26
  • 39
  • for reference, this will set the source port (udp_port) and will not set the source address. the address field will then get filled in by your network stack automatically once it figures out which interface/address to use based on the system's routing tables. – user2957811 Mar 19 '18 at 22:00
2

Client:

sock_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock_client.sendto("message", ("127.0.0.1", 4444))

Server:

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", 4444))
while(1):
    data, addr = sock.recvfrom(1024)
    print "received:", data

This code works. Python-2.7.

It seems you mixed client and server sockets, addresses or subnetworks.

Anton Glukhov
  • 3,507
  • 1
  • 15
  • 16