gpt4 book ai didi

c - 如何在C中使用UDP监听数据包?

转载 作者:太空宇宙 更新时间:2023-11-04 03:33:26 27 4
gpt4 key购买 nike

我写了这个 udp 接收 C 代码来监听正在流式传输的数据包,看起来代码没有进入 while 循环:代码的输出如下,然后它停在那里没有错误,尽管端口和 ip 都被正确定义并且发送数据有效:

正在初始化 Winsock...已初始化。这是创建的套接字:128套接字已创建。连接到套接字;然后它会停留在这里并且不会进入循环..

代码:

#include<stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <winsock2.h>
#include <fcntl.h>

#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "wsock32.lib")

int main(int argc , char *argv[])
{
printf("started \n");
WSADATA wsa;
SOCKET s;
struct sockaddr_in server, client_addr;
int recv_size =8192;// 2000000;
char ser[recv_size] ;
int count = 0;
int addr_len;
int bytes;
char *message , server_reply[recv_size];

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}

printf("Initialised.\n");

if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
{ printf("Could not create socket : %d" , WSAGetLastError());
}else{ printf("This is the socket that was created: %d \n", s); }

printf("Socket created.\n");

server.sin_addr.s_addr = inet_addr("192.168.10.103");
server.sin_family = AF_INET;
server.sin_port = htonl(25000);
addr_len = sizeof(struct sockaddr);

if (connect(s, (struct sockaddr *)&server, sizeof(server))<0)
{ puts("connect error");return 1 ;
}else {puts("connects to the socket"); }
while(1) {
// if ((recv_size = recv(s, server_reply, recv_size, 0)) == SOCKET_ERROR) {
// puts("failed at receive");
// }
puts("receiving from microzed");
bytes = recvfrom(s,ser,recv_size,0,(struct sockaddr *)&client_addr,&addr_len);
//ser[bytes] = '\0';
write(1,ser,bytes);

// printf("count: %d \n ",count = count+ 1);
// printf("data received: %d \n",ser);

}
puts("works \n");

// server_reply[recv_size] = '\0';
// printf("This is what the message reply is : %d, \n ",server_reply);

printf("finished \n");
return 0;
}

最佳答案

我假设它是 puts() 和 recv() 之间的某种“竞争条件”,因为没有其他任何东西出现,很明显 recvfrom() 正在阻塞,否则,你会查看其余的输出(即“work\n”)。

一种简单的测试方法是将套接字的模式设置为 NON_BLOCKING。

我已经尝试使用 MS Visual 2015 运行代码,它运行没有问题。输出:

started

Initialising Winsock...Initialised. This is the socket that was created: 200 Socket created. connects to the socket receiving from microzed

关于c - 如何在C中使用UDP监听数据包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361874/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com