Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send int over socket in C/C++

I have troubles with sending an array of ints over a socket. the code looks like this

Program 1: (running on windows)

int bmp_info_buff[3];

/* connecting and others */

/* Send informations about bitmap */
send(my_socket, (char*)bmp_info_buff, 3, 0);

Program 2: (running on neutrino)

/*buff to store bitmap information size, with, length */
int bmp_info_buff[3];

/* stuff */

/* Read informations about bitmap */
recv(my_connection, bmp_info_buff, 3, NULL);
printf("Size of bitmap: %d\nwidth: %d\nheight: %d\n", bmp_info_buff[0], bmp_info_buff[1], bmp_info_buff[2]);

It should print Size of bitmap: 64
width: 8
height: 8

Size of bitmap: 64
width: 6
height: 4096
What do I do wrong?

like image 315
Lukasz Avatar asked Jan 04 '13 13:01

Lukasz


People also ask

What does socket () do in C?

The socket() function shall create an unbound socket in a communications domain, and return a file descriptor that can be used in later function calls that operate on sockets. The socket() function takes the following arguments: domain. Specifies the communications domain in which a socket is to be created.

Can socket programming be done in C?

It extracts the first connection request on the queue of pending connections for the listening socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket. At this point, the connection is established between client and server, and they are ready to transfer data.

How do you send data from client to server in socket programming?

Create a socket with the socket() system call. Initialize the socket address structure as per the server and connect the socket to the address of the server using the connect() system call. Receive and send the data using the recv() and send(). Close the connection by calling the close() function.

What is send in socket programming?

The send() function sends data on the socket with descriptor socket. The send() call applies to all connected sockets. Parameter Description socket. The socket descriptor.


1 Answers

When you send the bmp_info_buff array as char array, the size of bmp_info_buff is not 3 but is 3 * sizeof(int)

The same for recv

Replace

send(my_socket, (char*)bmp_info_buff, 3, 0);
recv(my_connection, bmp_info_buff, 3, NULL);

by

send(my_socket, (char*)bmp_info_buff, 3*sizeof(int), 0);
recv(my_connection, bmp_info_buff, 3*sizeof(int), NULL);
like image 162
MOHAMED Avatar answered Oct 06 '22 00:10

MOHAMED