Skip to content

关于udp recvfrom #6

Answered by TANSixu
whateveraname asked this question in Q&A
Discussion options

You must be logged in to vote

感谢提问。这是一个非常好的问题。
先说答案:一次recvfrom中不会有第二个包的内容。

这是因为udp报文读取时并不是像tcp流一样按给定的length读取bytes,而是一次取出一整个包,然后截取给定的length,如果给定的length比一个包的实际大小小,那么这个包剩下的内容也会丢失(可以通过设置flag避免)。例如,如果一个udp包大小为1400 bytes,用户调用recvfrom(1000),那么这1400bytes会被全部取出,但只返回前1000 bytes,剩下的会丢掉。而如果一个udp包大小为1400,用户调用recvfrom(2000),那么返回的只有1400 bytes,因为一次只会读取一个包。

参考 recvfrom manpage:

  The recvfrom() function shall return the length of the message
       written to the buffer pointed to by the buffer argument. For
       message-based sockets, such as SOCK_RAW, SOCK_DGRAM, and
       SOCK_SEQPACKET, the entire message shall be read in a single
       operation. If a message is too long to fit in the supplied
       buffer, and MSG_PEEK is …

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by TANSixu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
good first issue Good for newcomers
2 participants