Catch_0x16
Catch_0x16

Reputation: 307

C++ Socket Buffer Size

This is more of a request for confirmation than a question, so I'll keep it brief. (I am away from my PC and so can't simply implement this solution to test).

I'm writing a program to send an image file taken via webcam (along with meta data) from a raspberryPi to my PC.

I've worked out that the image is roughly around 130kb, the packet header is 12b and the associated meta data another 24b. Though I may increase the image size in future, once I have a working prototype.

At the moment I am not able to retrieve this whole packet successfully as, after sending it to the PC I only ever get approx 64kb recv'd in the buffer.

I have assumed that this is because for whatever reason the default buffer size for a socket declared like:

SOCKET sock = socket(PF_INET, SOCK_STREAM, 0);

is 64kb (please could someone clarify this if you're 'in the know')

So - to fix this problem I intend to increase the socket size to 1024kb via the setsockopt(x..) command.

Please could someone confirm that my diagnosis of the problem, and proposed solution are correct?

I ask this question as I am away form my PC right now and am unable to try it until I get back home.

Upvotes: 0

Views: 5906

Answers (1)

G. Sliepen
G. Sliepen

Reputation: 7973

This most likely has nothing to do with the socket buffers, but with the fact that recv() and send() do not have to receive and send all the data you want. Check the return value of those function calls, it indicates how many bytes have actually been sent and received.

The best way to deal with "short" reads/writes is to put them in a loop, like so:

char *buf;  // pointer to your data
size_t len; // length of your data
int fd;     // the socket filedescriptor

size_t offset = 0;
ssize_t result;
while (offset < len) {
  result = send(fd, buf + offset, len - offset, 0);
  if (result < 0) {
     // Deal with errors here
  }
  offset += result;
}

Use a similar construction for receiving data. Note that one possible error condition is that the function call was interrupted (errno = EAGAIN or EWOULDBLOCK), in that case you should retry the send command, in all other cases you should exit the loop.

Upvotes: 1

Related Questions