KianP KianP - 1 year ago 92
Linux Question

Sending Image Over Linux C TCP

I am trying to maintain a persistent connection from the browser with a simple HTTP server written in pure C.

The response to any HTML/text is fine, but I am having trouble sending image files. I have realized that a header (namely because of

) is compulsory when a browser is connecting. Therefore, I first send the header, and then the image. The server Code is like this:

// section relating to responding an image
else if(!strncmp(buf, "GET /testpic.jpg", 16)) {
FILE * _fdimg = fopen("testpic.jpg", "rb");
struct stat st;
stat("testpic.jpg", &st);

char send_buffer[100000];

int read_size = fread(send_buffer, 1, st.st_size , _fdimg);
// regradless of the third param, the read_size value is 50029 which is the correct size of the image

// header_image is a char[] corresponding to appropriate headers with correct content-length

write(socket, header_img, sizeof(header_img));
write(socket, send_buffer, st.st_size);

// This works, but I can't send the header with this function.
// sendfile(socket, _fdimg, NULL, 600000);

Now the browser will understand the persistent connection, will fetch the correct amount of data from the socket, but the file sent over the socket has one small problem, there is an extra 00 at the beginning of it (in hex format)

enter image description here

Any suggestions?

Note: I have also tried sending the header with normal
and the image with
systemcall, but the browser will not recognize this correctly and the spinner in the page will keep loading

Note: the image size is 50028 bytes. Both st.st_size and read_size values are correct and are equal to the actual file size. I perceive that the process of reading from the file is ok, but there is an index mismatch or some kind of error when I am copying it to the buffer.

Update Headers :

char header_img[]=
"HTTP/1.1 200 OK\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 50029\r\n\r\n";

Answer Source

You don't show how you create your header, but you must be aware of the fact that in C, strings are 0x00-terminated:

header-field: value\n\0x00

You're probably not sending

header-field: value\nIMAGEDATA


header-field: value\n\0x00IMAGEDATA

because you sent the whole string, not just it's actual non-terminator chars.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download