簡體   English   中英

在 C/C++ 中通過套接字發送 int

[英]Send int over socket in 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()的 size 參數以字節為單位,而不是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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM