Sending Images over Sockets in C

Posted by Takkun on Stack Overflow See other posts from Stack Overflow or by Takkun
Published on 2012-10-27T04:56:26Z Indexed on 2012/10/27 5:00 UTC
Read the original article Hit count: 116

Filed under:
|

I'm trying to send an image file through a TCP socket in C, but the image isn't being reassembled correctly on the server side. I was wondering if anyone can point out the mistake?

I know that the server is receiving the correct file size and it constructs a file of that size, but it isn't an image file.

Client

//Get Picture Size
printf("Getting Picture Size\n");
FILE *picture;
picture = fopen(argv[1], "r");
int size;
fseek(picture, 0, SEEK_END);
size = ftell(picture);

//Send Picture Size
printf("Sending Picture Size\n");
write(sock, &size, sizeof(size));

//Send Picture as Byte Array
printf("Sending Picture as Byte Array\n");
char send_buffer[size];
while(!feof(picture)) {
    fread(send_buffer, 1, sizeof(send_buffer), picture);
    write(sock, send_buffer, sizeof(send_buffer));
    bzero(send_buffer, sizeof(send_buffer));
}

Server

//Read Picture Size
printf("Reading Picture Size\n");
int size;
read(new_sock, &size, sizeof(1));

//Read Picture Byte Array
printf("Reading Picture Byte Array\n");
char p_array[size];
read(new_sock, p_array, size);

//Convert it Back into Picture
printf("Converting Byte Array to Picture\n");
FILE *image;
image = fopen("c1.png", "w");
fwrite(p_array, 1, sizeof(p_array), image);
fclose(image);

© Stack Overflow or respective owner

Related posts about c

    Related posts about sockets