Disconnect and reconnect the connected datagram connector

I am trying to create an iterative server based on datagram sockets (UDP). It causes a connection to the first client, which it receives from the first call to recvfrom () (yes, I know that this is not a real connection). After serving this client, I disconnect the UDP socket (calling connect with AF_UNSPEC), then I call recvfrom () to get the first packet from the next client.

Now the problem is that calling recvfrom () in the second iteration of the loop returns 0. My clients never send empty packets, so what could happen.

This is what I am doing (pseudo code):

s = socket(PF_INET, SOCK_DGRAM, 0)

bind(s)

for(;;)
{
  recvfrom(s, header, &client_address)  // get first packet from client
  connect(s,client_address)  // connect to this client
  serve_client(s);
  connect(s, AF_UNSPEC); // disconnect, ready to serve next client
}

EDIT: , . , , ( ).

+3
3

connect() SOCK_DGRAM.

connect , . , .

: , -, . , , () ed . "", . , , connect() DGRAM - , , ?

, 0 recvfrom(), ( ) (, ). , , - .

, .

, ; .

UDP- "" ; .

+3

man connect:

...
If the initiating socket is not connection-mode, then connect()
shall set the socket’s peer address, and no connection is made.
For SOCK_DGRAM sockets, the peer address identifies where all
datagrams are sent on subsequent send() functions, and limits
the remote sender for subsequent recv() functions. If address
is a null address for the protocol,  the  socket’s  peer  address
shall be reset.
...
0

Just a fix in case someone stumbles upon this, like me. To disable connect (), you must call the sa_family sockaddr parameter set to AF_UNSPEC. Not just passed AF_UNSPEC.

-1
source

Source: https://habr.com/ru/post/1709103/


All Articles