通过套接字发送int,c,C++
我在通过套接字发送int数组时遇到麻烦。 的代码看起来是这样通过套接字发送int,c,C++
程序1(运行在Windows)
int bmp_info_buff[3];
/* connecting and others */
/* Send informations about bitmap */
send(my_socket, (char*)bmp_info_buff, 3, 0);
计划2(上中微子运行)
/*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]);
应该打印 位图的大小:64
宽度:8
身高:8
位图大小:64
宽度:6
高度:4096
我该怎么做?
当您发送bmp_info_buff
数组作为字符数组的bmp_info_buff
大小不是3,而是3 * sizeof(int)
同为recv
通过
更换send(my_socket, (char*)bmp_info_buff, 3, 0);
recv(my_connection, bmp_info_buff, 3, NULL);
send(my_socket, (char*)bmp_info_buff, 3*sizeof(int), 0);
recv(my_connection, bmp_info_buff, 3*sizeof(int), NULL);
send()
和recv()
的大小参数以字节为单位,而不是int
s。您发送/接收的数据太少。
您需要:
send(my_socket, bmp_info_buff, sizeof bmp_info_buff, 0);
和
recv(my_connection, bmp_info_buff, sizeof bmp_info_buff, 0);
还要注意:
- 这使得以字节排列顺序问题你的代码是敏感的。
-
int
的大小在所有平台上都不相同,您也需要考虑这一点。 - 无需转换指针参数,它是
void *
。 - 您还应该添加代码来检查返回值,I/O可能会失败!
-
recv()
的最后一个参数不应该是NULL
,因为在您的代码中,它是一个标记整数,就像在send()
中一样。
+1。但是,大家不知道'sizeof'关键字或什么? – 2013-01-04 14:02:01
+1字节字节顺序的东西! –
以网络顺序发送内容也是一个好主意。 –
感谢它的工作。 – Lukasz