6

I read in MSDN about the send() and recv() function, and there is one thing that I'm not sure I understand.

If I send a buffer of size 256 for example, and receive first 5 bytes, so the next time I call the recv() function, it will point to the 6th byte and get the data from there?

for example :

char buff[256];
memcpy(buff,"hello world",12);
send(sockfd, buffer, 100) //sending 100 bytes

//server side:
char buff[256];
recv(sockfd, buff, 5) // now buffer contains : "Hello"?
recv(socfd, buff,5) // now I ovveride the data and the buffer contains "World"?

thanks!

user1386966
  • 3,302
  • 13
  • 43
  • 72
  • 1
    `recv()` doesn't change where your buffer points.. but it tells you how much it read so you can continue from where it left off. You need to adjust the pointer and size you pass it yourself, though. – Dmitri Nov 29 '14 at 19:08

2 Answers2

8

The correct way to receive into a buffer in a loop from TCP in C is as follows:

char buffer[8192]; // or whatever you like, but best to keep it large
int count = 0;
int total = 0;

while ((count = recv(socket, &buffer[total], sizeof buffer - total, 0)) > 0)
{
    total += count;
    // At this point the buffer is valid from 0..total-1, if that's enough then process it and break, otherwise continue
}
if (count == -1)
{
    perror("recv");
}
else if (count == 0)
{
    // EOS on the socket: close it, exit the thread, etc.
}
user207421
  • 305,947
  • 44
  • 307
  • 483
  • 4
    I know this is old but I think it should be: `while ((count = recv(socket, &buffer[total], sizeof (buffer) - total, 0)) > 0) {` – Darrell Jul 07 '20 at 18:54
2

You have missed the principal detail - what kind of socket is used and what protocol is requested. With TCP, data is octet granulated, and, yes, if 256 bytes was sent and you have read only 5 bytes, rest 251 will wait in socket buffer (assuming buffer is larger, which is true for any non-embedded system) and you can get them on next recv(). With UDP and without MSG_PEEK, rest of a single datagram is lost, but, if MSG_PEEK is specified, next recv() will give the datagram from the very beginning. With SCTP or another "sequential packet" protocol, AFAIK, the same behavior as with UDP is got, but I'm unsure in Windows implementation specifics.

Netch
  • 4,171
  • 1
  • 19
  • 31
  • If it doesn't fit into the receiver's socket receive buffer it will be in the sender's socket send buffer, and if it doesn't fit there it hasn't been sent yet. – user207421 May 07 '18 at 02:29