我正在寫在C++客戶端應用程序經由UDP的廣播接收的二進制數據,但是我無法接收任何超出前4個字節,而不管緩衝區大小。我在Wireshark中檢查了數據包,我可以看到我的機器正在接收大約1200字節的數據。當我將它與我的客戶正在接收的數據進行比較時,我可以看到我正在收到數據包,但是剩餘的數據丟失了。這裏是我的代碼:的recv只得到第一個4個字節包
#define BUFFERSIZE 4096
int main()
{
struct addrinfo hints, *servinfo, *p;
int sockfd, i, nbyt;
int *buf = (int*) malloc(BUFFERSIZE);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "9011", &hints, &servinfo);
sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen);
FILE *file;
file = fopen("file.txt", "w+");
for (i=0;i<=45;i++)
{
nbyt = recv(sockfd, buf, BUFFERSIZE, 0);
fprintf(file, "%s %d; %s %x\n", "Bytes received:", nbyt, "Message:", *buf);
}
fclose(file);
close(sockfd);
free(buf);
printf("%s\n", "Execution ended.");
return 0;
}
的一些數據我收到的一個例子:
Bytes received: 1131; Message: 5b0
Bytes received: 1131; Message: 5b3
Bytes received: 1131; Message: 5b6
Bytes received: 1092; Message: 4e0
我試過設置插座與MSG_DONTWAIT
標誌無阻塞的,因爲這將固定問題的一個類似的Python應用程序,然而這僅會返回錯誤:
Bytes received: -1; Message: 0
我是比較新的C++和插座,所以它可能有一些,我只是沒有看到。希望有人能幫我弄清楚什麼是錯的?如有必要,我可以提供更多信息。
其中C++ ...... – neagoegab
fprintf中是問題。 – neagoegab
數據在緩衝區中。 %x使printf在buf指向的位置查找一個無符號的十六進制整數。所以你的程序正在做你要做的事情。你可能還想要別的東西。請注意,在您的recv()調用中,您設置了BUFFERSIZE _bytes_的限制,而您分配的緩衝區至少大四倍,具體取決於您的平臺的int大小。分配字符緩衝區,像現在這樣爲數據調用recv(),並將緩衝區指針傳遞給處理程序以獲取二進制數據。 printf()不是查看二進制內容的好選擇。 – arayq2