Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending images over sockets

Tags:

c

sockets

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(int));

//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);

Edit: Fixed sizeof(int) in server code.

like image 235
Takkun Avatar asked Oct 27 '12 04:10

Takkun


People also ask

Is it possible to send image through socket in Java?

Many peoples found it difficult to do it. many times we need to send images through network socket from one computer to another computer. Now we are going to see how we can send image through socket in java.

How to send an image over TCP?

A better way to send the image would be to use BinaryFormatter. eg, some snippets from my own code to send an image every second... TcpClient client = new TcpClient (); try { client.Connect (address, port); // Retrieve the network stream.

How to send a photo to a UDP server?

User starts server with a button and client selects photo by opening the file dialog of computer. At last sends the image but be careful about the photo size because UDP cannot transmit much large data.

Does at last send the image in UDP?

At last sends the image but be careful about the photo size because UDP cannot transmit much large data.


1 Answers

you need to seek to the beginning of the file before you read

fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);

or use fstat to get the file size.

like image 82
iabdalkader Avatar answered Sep 22 '22 05:09

iabdalkader