接收UDP错误:连接被拒绝

前端之家收集整理的这篇文章主要介绍了接收UDP错误:连接被拒绝前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图通过UDP在特定端口发送字符串HI到服务器,然后接收响应.但是,在尝试使用recvfrom()获取响应后,我被卡在阻塞状态.我尝试使用连接的UDP,但我得到:

Error receiving in UDP: Connection refused

这可能是什么原因?服务器不在我的控制之下,但我知道它的工作正常.

我已经添加代码

int sockfdudp;
char bufudp[MAXDATASIZE],port[6];
struct addrinfo hints,*servinfo,*p;
struct sockaddr_storage addr;   
int rv;
char s[INET6_ADDRSTRLEN];
int bytes_recv,bytes_sent;
socklen_t len;

scanf("%s",port);
printf("UDP Port: %s \n",port);

// Start connecting to datagram server  
memset(&hints,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;

if ((rv = getaddrinfo(SERVER_NAME,port,&hints,&servinfo)) != 0) {
    fprintf(stderr,"getaddrinfo: %s\n",gai_strerror(rv));
    return 1;
}

// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
    if ((sockfdudp = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1) {
        perror("Creating datagram socket");
        continue;
    }

if (connect(sockfdudp,p->ai_addr,p->ai_addrlen) == -1) {
        close(sockfdudp);
        perror("Connecting stream socket");
        continue;
    }
    break;
}

if (p == NULL) {
    fprintf(stderr,"ClientUDP: Failed to bind socket\n");
    return 2;
}


freeaddrinfo(servinfo);

if ((bytes_sent = sendto(sockfdudp,UDP_MSG,strlen(UDP_MSG),p->ai_addrlen)) == -1) {
    perror("ClientUDP: Error sending data");
    exit(1);
}
printf("Data %s sent\n",UDP_MSG );     

len = sizeof(struct sockaddr_storage);

if ((bytes_recv = recvfrom(sockfdudp,bufudp,MAXDATASIZE-1,(struct sockaddr*)&addr,&len)) == -1) {
    perror("Error receiving in UDP");
    exit(1);
}

printf("Bytes recv %d\n",bytes_recv);  

bufudp[bytes_recv] = '\0';

printf("ClientUDP: Received\n %s \n",bufudp );    

close(sockfdudp);

return 0;

解决方法

有可能是将某些东西发送给不在该特定端口上收听的服务器.
这将导致icmp消息被发回,并且您的下一个recvfrom将在连接套接字的情况下返回错误.

检查tcpdump或wireshark在线上发生了什么.

原文链接:https://www.f2er.com/c/112567.html

猜你在找的C&C++相关文章