Send int over socket, c, c ++

I am having trouble sending an ints array through a socket. The code is as follows:

Program 1 (works in windows)

int bmp_info_buff[3]; /* connecting and others */ /* Send informations about bitmap */ send(my_socket, (char*)bmp_info_buff, 3, 0); 

Program 2 (runs on neutrinos)

 /*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 needs to print. Bitmap size: 64
width: 8
height: 8

Bitmap Size: 64
width: 6
height: 4096
What am I doing wrong?

+4
source share
2 answers

When sending the bmp_info_buff array as a char array, the size of bmp_info_buff not 3, but 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); 
+7
source

The size argument for send() and recv() is in bytes, not int s. You are sending / receiving too little data.

You need:

 send(my_socket, bmp_info_buff, sizeof bmp_info_buff, 0); 

and

 recv(my_connection, bmp_info_buff, sizeof bmp_info_buff, 0); 

Also note:

  • This makes your code sensitive to byte problems.
  • The int size is not the same on all platforms, you also need to consider this.
  • No need to specify a pointer argument, void * .
  • You should also add code to check return values, I / O failure!
  • The last argument to recv() should not be NULL , as in your code, this is an integer number of flags, as in send() .
+6
source

All Articles