UDP socket sendto () functions
I get an error if I want to write on my udp socket like this. According to the document, there should be no problem. I don't understand why bind () works 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 = {}
Mistake:
udp_server.sendto('', ('192.0.0.1', 14550) )
socket.error: [Errno 22] Invalid argument
source to share
The error indicates the presence of an invalid argument. Upon reading the code, I can tell that the offending argument is the IP address:
- you bind your socket to
127.0.0.1
- you are trying to send data to
192.0.0.1
which to another network
If you want to send data to a host by IP address 192.0.0.1
, bind the socket to a local network interface on the same network or a network that can find a route to192.0.0.1
I have a (private) local network in 192.168.56.*
, if I bind a socket to 192.168.56.x
(x is the local address), I can send data to 192.168.56.y
(y is the server address); but if i bind to 127.0.0.1
i get IllegalArgumentException
.
source to share
Customer:
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.
You seem to be mixing sockets, addresses, or subnets of clients and servers.
source to share