I have a udp server in python that i'm testing out by sending packets with netcat -u server_ip server_port
on the udp server, I can receive the packets with
data,addrport = socket.recvfrom(some_number)
— I can read the data received and see the other socket's address port with addrport
.
But if I try to use socket.getpeername()
on the same variable instead it gives the OSError: [Errno 107] Transport endpoint is not connected
error.
What causes this? I'm confused as my netcat terminal doesn't close after sending, which I assume means its already connected to my UDP socket.
CodePudding user response:
I can receive the packets with
data,addrport = socket.recvfrom(some_number)
recvfrom
means that you are working with an unconnected UDP socket, i.e. the case where a single socket could receive packets from various sources and also send data to various sources using sendto
. getpeername
instead expects a connected socket, i.e. one which will only receive data from a single source (using recv
not recvfrom
) and only send to a single source (using send
not sendto
). This is the case with TCP established sockets (the ones returned by accept
) but also with UDP socket which are explicitly connected by calling connect
.