首页 文章

没有bind()的UDP客户端不接收数据

提问于
浏览
2

我从binarytides参考了UDP客户端程序,我能够将UDP数据包发送到UDP服务器,这是我的嵌入式设备,该设备回显UDP消息 .

在这个PC-UDP客户端代码中,它应该得到回显的消息,但我没有得到任何回声 . 所以我在我的PC上运行一个UDP服务器,它监听传入的数据并打印它,我能够看到来自我的嵌入式设备的回显消息 .

当我在代码中的while(1)循环之前添加这些行时,现在我能够看到Echoed back消息 .

//setup address structure
memset((char *) &si_server, 0, sizeof(si_server));
si_server.sin_family = AF_INET;
si_server.sin_port = htons(PORT);
si_server.sin_addr.S_un.S_addr = INADDR_ANY;

if( bind(s ,(struct sockaddr *)&si_server , sizeof(si_server)) == SOCKET_ERROR)
{
    printf("Bind failed with error code : %d" , WSAGetLastError());
    exit(EXIT_FAILURE);
}
puts("Bind done");

有关可能导致问题的原因的任何想法?

1 回答

  • 6

    嗨,最后我从EJP answer找到答案

    It is only necessary to bind() a server, because the clients need a fixed port number to send to. A client needn't bind() at all: an automatic bind() will take place on the first send()/sendto()/recv()/recvfrom() using a system-assigned local port number.

    在wireshark的帮助下,我能够看到我的PC正在从端口53701发送数据,并且在第一个sendto()这个端口被自动绑定,因此必须进行显式绑定 .

相关问题