1

i have many processes running, send messages to each other by socket. among them, there are two processes, the first one send 24 bytes to the other one(i'm sure it's 24 bytes because i get it from the return value of sendto()), but on the receiver side i only received 16 bytes.

nRecvbytes = recvfrom(sock, recvbuf, recvlen, 0, addr, sa_len)

the recvlen is 24 bytes, but nRecvbytes is 16 bytes. And this case is not stable, as i run this for many times, this situation sometimes happen but sometimes not. Does anyone have any idea why this may happen? thanks!

user2810081
  • 589
  • 1
  • 8
  • 27

2 Answers2

3

Its common that received bytes are less than the specified length or length of data in the send function.

You need to call receive multiple times until you get data as much as you want. The packets can be broken down into multiple packets which can result in such cases.

Rohan
  • 52,392
  • 12
  • 90
  • 87
  • 1
    @glglgl - OK, maybe you habve other bugs too. Fix the one you know about first - fix your protocol to accommodate the byte-stream nature of TCP, as suggested by others. – Martin James Nov 25 '13 at 10:55
  • 1
    The size of the TCP packets is unrelated to the number of bytes you provide to any particular send() call. The TCP layer will stuff bytes into packets in whatever way it feels appropriate to do so (based on the current network conditions); its only constraint is that the bytes must be received in the same order they were sent. – Jeremy Friesner Apr 04 '17 at 16:48
0

Please check out flags you are using for receive function

Behavior you are experiencing is similar to situation when MSG_PEEK flag is used.

MSG_PEEK, Leave received data in queue.

With MSG_WAITALL flag you can just read all available data to buffer.

MSG_WAITALL, Attempt to fill the read buffer.

More details you can find on http://pubs.opengroup.org/onlinepubs/009695399/functions/recv.html

Amit Vujic
  • 1,632
  • 1
  • 24
  • 32