1

When I listen to TCP or UDP socket with

ssize_t recv(int sockfd, void *buf, size_t len, int flags);

Or

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flag , struct sockaddr *src_addr, socklen_t *addrlen);

There is argument called len

In linux ,what is the maximum buffer len that I can read with those function?is that 65336 ? Where is that defines?

What will happen if in socket there are more bytes than this number? They will dropped out? Or I will read them in the next loop?

Keystone
  • 165
  • 1
  • 9

2 Answers2

2

Since len is of type size_t, its maximum size is defined by SIZE_MAX. The C standard specifies that SIZE_MAX must be at least 65535. However, there is no upper bound, so its actual value depends on the compiler.

size_t and SIZE_MAX are defined in <stdint.h>.

What will happen if there are more bytes than the specified len depends on what type of socket you have.

If you have a TCP socket (of type SOCK_STREAM), if there are more bytes waiting to be read than the value of len, then they will be read the next time you call recv().

However, if your socket is of type SOCK_DGRAM (an UDP socket), a call to recvfrom() will always read an entire datagram. If the datagram's length is larger than len, the first len bytes will be read into your buffer and the rest will be lost.

In this case, recvfrom() returns -1 and sets errno to EMSGSIZE, so that's how you test if this happened.

0

In theory, you can read as large of a buffer as you want. The maximum value of size_t is guaranteed by the C standard to be at least 65535, however on modern Linux systems it will be at least 232-1, if not 264-1.

For TCP, since it is a streaming protocol, any bytes left unread will remain in the buffer waiting to be read on the next iteration.

For UDP, only one full datagram is read at a time, and if the buffer isn't big enough to hold a datagram any excess bytes are lost. Additionally, because UDP doesn't have reliability built in to the protocol, datagrams can be lost if not read quickly enough.

dbush
  • 205,898
  • 23
  • 218
  • 273