raptor
raptor

Reputation: 760

C Socket - Determine data length

I wrote a little SocketWrapper in C just for learning and it works. I'm sending a GET-Request and receiving a buffer[1024]. But the content I would like to read is often longer than 1024. How can I determine the length and receive the whole data?

#include <stdio.h>
#include <stdbool.h>

#include "lib/output.h"
#include "lib/network.h"

int main(int argc, char *argv[]) {
debug_verbose = true;

struct IPv4_CLIENT client;
client = socketIPv4("google.com", 80);

if(socketIPv4_connect(client) < 0) {
    error("Connect failed!");
    return -1;
}   

char send_buffer[256];
bzero(send_buffer, 256);

printline("Send: ");
fgets(send_buffer, 255, stdin);

socketIPv4_write(client, send_buffer);

char receive_buffer[1024];
socketIPv4_read(client, receive_buffer, 1024);
hexdump(receive_buffer, 1024);

socketIPv4_close(client);

return 0;
}

Upvotes: 0

Views: 2872

Answers (2)

VoidPointer
VoidPointer

Reputation: 3097

You cannot determine the total length of data to receive when using TCP/UDP. So you should implement a protocol over this underlying protocol to determine the total length to receive. So once you come to know the size, you expect and read those data.

Here, in your case of HTTP, the standard defines a separate header called Content-Length for the purpose of giving the total length of the body. But, to read the headers, you can receive arbitrary amount of data till you receive all headers and then the given amount of body content.

Read the spec to understand headers, body, delimiters..

Upvotes: 2

alk
alk

Reputation: 70883

Consider one of the two following approaches:

  • Send the size of the data you want to transmit before the actual data. Use a fixed length format to transmit the size.

  • Define any delimiter marking the end of the data, and continue reallocating the receive buffer until the delimiter had been received.

Upvotes: 2

Related Questions