通过socket,c,c ++发送int
在socket上发送一组int有麻烦。 代码看起来像这样
程序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
数组作为char数组发送时, 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()
的size参数以字节为单位,而不是int
。 您发送/接收的数据太少。
你需要:
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()
。