gpt4 book ai didi

c++ - Asio UDP 套接字接收失败

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:13:59 25 4
gpt4 key购买 nike

尝试使用此代码发送/接收 Asio UDP 套接字(boost less 版本)

asio::io_service service;
asio::ip::udp::socket sock(service);
asio::ip::udp::endpoint endpoint(asio::ip::address::from_string("127.0.0.1"), 20100);

sock.connect(endpoint);
sock.send(buffer("testing\n"));

std::string buffer;
size_t length = sock.receive(asio::buffer(buffer)); <--- spawn exception

但出现以下错误:

An existing connection was forcibly closed by the remote host

这里有什么问题吗?感谢您的帮助!

最佳答案

我不知道你是如何构建你的 udp 服务器的,但我猜它有问题。我编写了一个示例程序来解释您收到的错误消息:

#include <stdio.h>  
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
struct sockaddr_in addr;
int fd, cnt, ret;

if ((fd=socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
printf("error");
exit(1);
}

memset(&addr, 0, sizeof(addr));
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
addr.sin_port=htons(9090); // address which is not bound

ret = connect(fd,(struct sockaddr *)&addr,sizeof(addr));
char buf[512];

cnt = send(fd, "hello", sizeof("hello"), 0);
if(cnt < 0)
perror("send:");
cnt = recv(fd, buf, 512, 0); // error: Connection refused
if(cnt < 0)
perror("recv:");

return 0;
}

我尝试将数据发送到本地主机的 udp 端口​​ 9090 或任何没有 udp 套接字绑定(bind)到端口 9090 的主机。send() 成功但 recv() 失败。根据man page for udp :

All fatal errors will be passed to the user as an error return even when the socket is not connected. This includes asynchronous errors received from the network. You may get an error for an earlier packet that was sent on the same socket. This behaviour differs from many other BSD socket implementations which don't pass any errors unless the socket is connected. Linux's behaviour is mandated by According to the rfc 1122

上面写着:

UDP MUST pass to the application layer all ICMP error messages that it receives from the IP layer. Conceptually at least, this may be accomplished with an upcall to the ERROR_REPORT routine

send() 成功了,但是它导致了一个 ICMP 错误消息(你可以用 tcpdump 看到它),然后 recv() 看到这个错误(对于在同一套接字上发送的较早数据包,您可能会收到错误),因此失败。

关于c++ - Asio UDP 套接字接收失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36401841/

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