简体   繁体   中英

C UDP sockets, where do packets are stored before to be retrieved by recvfrom?

I am creating a little application in C using UDP sockets and I am using the following recvfrom function:

int recvfrom(int s, void *buf, int len, unsigned int flags struct sockaddr *from, socklen_t *fromlen); 

I am actually wondering from where the data are retrieved by this function because in my application, I receive different packets and once I'm sure that I received all the packets, I use a loop to retrieve several packets.

It seems to work (maybe I am lucky ;) but I don't really understand where my packets are stored before to be retrieved by the multiple calls to recvfrom in my loop.

Thank you in advance for your help and have a good day ! Alex

They are held in the kernel, in some internal buffer. Should that buffer fill (ie if your application stops calling recvfrom ) the kernel will start dropping datagrams.

It's important to realize that both sendto and recvfrom are just fancy memcpy -like calls - none of them actually "send" or "receive" anything. Sendto copies data to the kernel, and then the kernel tries to actually put it into packets and so on. Similarly, by the time you call recvfrom , the data has already been received and recvfrom only copies it to your userspace buffer .

All received packets are stored in kernel queue. It's a fixed length queue. If the application doesn't receive packets ,it will overwrite old one. And update its queue. So whenever you call receivefrom a old packet available is delivered to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM