When sending a length field in a TCP stream, you need to solve two things:
- what length should have a length (1 byte, 2 bytes, 4 bytes, variable length)
- what's the point of using i
4 (.. big-endian). htonl ntohl (native) byte order (little-endian ) .
, :
size_t length = strlen(data);
uint32_t nlength = htonl(length);
send(sock, &nlength, 4, 0);
send(sock, data, length, 0);
, :
uint32_t length, nlength;
recv(sock, &nlength, 4, 0);
length = ntohl(nlength);
data = malloc(length+1);
recv(sock, data, length, 0);
data[length] = 0;
- : ; recvs , . .
. , recv , , , ,
int length_bytes = 0;
while(length_bytes < 4){
int read = recv(sock, ((char*)&nLength)+length_bytes, 4-length_bytes, 0);
if (read == -1) some_error_occurred_check_errno();
length_bytes += read;
}