UDP socket sendto() functions

戏子无情 提交于 2021-02-07 04:11:00

问题


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

回答1:


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.




回答2:


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

udp_server.bind(('0.0.0.0', udp_port))



回答3:


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.



来源:https://stackoverflow.com/questions/30268008/udp-socket-sendto-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!