Send int over socket in C/C++
Asked Answered
N

2

6

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?

Noontime answered 4/1, 2013 at 13:58 Comment(0)
A
9

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);
Anton answered 4/1, 2013 at 14:1 Comment(2)
But what about byte ordering issues? Writing ints from a big-endian machine to a little-endian machine requires usage of htonl, ntohl, etc.Brannon
In addition, make sure you check the return values from send and recv. They're the only way to be sure what really happened.Waxy
V
8

The size argument to send() and recv() is in bytes, not ints. You're 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 endianness issues.
  • The size of int is not the same on all platforms, you need to consider this, too.
  • No need to cast the pointer argument, it's void *.
  • You should also add code to check the return values, I/O can fail!
  • The last argument to recv() shouldn't be NULL as in your code, it's a flags integer just as in send().
Vulcan answered 4/1, 2013 at 14:0 Comment(2)
+1. But don't people know about the sizeof keyword or what?Hellbox
Also, there is an issue about possible 32/64bit mismatch to add.Hadji

© 2022 - 2024 — McMap. All rights reserved.