send int over socket, c, c++

人盡茶涼 提交于 2019-12-05 08:21:14

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

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().
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!