Reputation: 38163
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:
read
on a UDP socket is perfectly fine (if I don't need the src_addr
)?write
on UDP socket (as now I set the destination address in sendto
's dest_addr
parameter)?Upvotes: 10
Views: 19873
Reputation: 310884
read()
on a UDP socket is perfectly fine if you don't need the source address.write()
if you connect()
the UDP socket to the destination.Upvotes: 7
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:
send
/recv
if you're in a connection oriented mode e.g. TCPsendto
/recvfrom
mainly for connectionless communications e.g UDP 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