Kiril Kirov
Kiril Kirov

Reputation: 38163

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

According to the man pages:

The only difference between send() and write(2) is the presence of flags. With a zero flags argument, send() is equivalent to write(2). Also, the following call send(sockfd, buf, len, flags); is equivalent to sendto(sockfd, buf, len, flags, NULL, 0);

and

The recv() call is normally used only on a connected socket (see connect(2)) and is identical to recvfrom() with a NULL src_addr argument.

Also, if I'm not wrong (couldn't find it in the man pages), recv with flags == 0 is equivalent to read (analogue to write and send).


So:

Upvotes: 10

Views: 19873

Answers (2)

user207421
user207421

Reputation: 310884

  • Using read() on a UDP socket is perfectly fine if you don't need the source address.
  • You can use write() if you connect() the UDP socket to the destination.

Upvotes: 7

edmz
edmz

Reputation: 8494

Also, if I'm not wrong (couldn't find it in the man pages), ::recv with flags == 0 is equivalent to ::read (analogue to ::write and ::send)

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

With UDP, however, there's no connection so a call like this:

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

would not make sense as no destination is provided (EDESTADDRREQ). Instead, when you read a packet, you know where it is coming from and you may want to use that IP in case something looks wrong, for istance.

My advise is:

  • Use send/recv if you're in a connection oriented mode e.g. TCP
  • Use sendto/recvfrom mainly for connectionless communications e.g UDP
  • Use write/read if you will not specify any flag and for raw I/O (the aforementioned functions may be consider as higher level ones)

I would not advise a single class which handles both protocols but rather two specialized ones; don't mix the protocols.

Upvotes: 2

Related Questions