Using write () / read () on a UDP socket?

According to the man pages:

The only difference between send () and write (2) is the presence of flags. With a null flag argument, send () is equivalent to write (2). In addition, the next call to send (sockfd, buf, len, flags); equivalent to sendto (sockfd, buf, len, flags, NULL, 0);

and

The recv () call is usually used only for the connected socket (see connect (2)) and is identical to recvfrom () with the NULL argument src_addr.

In addition, if I'm not mistaken (I did not find it on the manual pages), recv with flags == 0 equivalent to read (analogue of write and send ).


So:

  • Does this mean that using read in UDP juice is fine (if I don't need src_addr )?
  • Is there a way to use write on a UDP socket (since I have now set the destination address to sendto dest_addr )?
+5
source share
2 answers
  • Using read() in UDP juice is great if you don't need the source address.
  • You can use write() if you connect() UDP socket for the destination.
+4
source

In addition, if I am not mistaken (I could not find it on the man pages), :: recv with flags == 0 is equivalent to :: read (analogue to :: write and :: send)

Yes, this is correct if the file descriptor is a socket: send / recv will not work otherwise with EBADF.
And it is also true that in the connection-oriented model, send equivalent to sendto and recv - recvfrom with NULL sockaddr * , because the protocol already provides them.

In UDP, however, there is no connection, so the call is:

 // assume fd to be an UDP socket write(fd, buff, bytes) 

does not make sense, since the destination is not provided (EDESTADDRREQ). Instead, when you read the package, you know where it comes from, and you can use this IP address in case something looks wrong for istance.

My advice:

  • Use send / recv if you are in connection-oriented mode, for example. TCP
  • Use sendto / recvfrom mainly for connectionless connections like UDP
  • Use write / read if you do not specify a flag for raw I / O (the above functions may be considered higher)

I would not recommend a single class that handles both protocols, but rather two specialized ones; do not mix protocols.

+3
source

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


All Articles