【问题标题】:socket connection recvfrom no response C++套接字连接recvfrom无响应C ++
【发布时间】:2015-08-04 07:10:37
【问题描述】:

我正在尝试从 UDP 广播中获取数据,但 recvfrom 函数没有响应。连接、绑定,一切看起来都很好。

会不会是直播有问题?

无论如何我可以检查确切的错误吗?

#include <iostream>
using namespace std;
//#include <ServerSocket.h>
#include <cstring>      
#include <sys/socket.h> 
#include <netdb.h>      
#include <stdio.h>
#include <stdlib.h>

int main()
{

    enter code here
    int status;
    int socketfd;
    int enableMulticast = 1;         // Argument for set socket 

    struct addrinfo host_info;       // The struct that getaddrinfo() fills up with data.
    struct addrinfo *host_info_list; // Pointer to the to the linked list of host_info's.
    struct sockaddr_in socketAddr;
    unsigned char incomming_data_buffer[IN_LEN];
    socklen_t socklen;
    #ifndef IN_LEN    
    #define IN_LEN 4096
    #endif  

    memset(&host_info, 0, sizeof host_info);
    memset(&socketAddr, 0, sizeof(struct sockaddr_in));

    cout << "Setting up the structs..."  << endl;

    host_info.ai_family = AF_UNSPEC;     // IP version not specified. Can be both.
    host_info.ai_socktype = SOCK_DGRAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP.
    host_info.ai_protocol = IPPROTO_UDP; // The protocol type for UDP. If left as zero, it will return all types


    status = getaddrinfo("UDP IP Address","Port", &host_info, &host_info_list);

    socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
                      host_info_list->ai_protocol);
    if (socketfd == -1)  cout << "socket error " ;
    else cout << "socket created successfully " ;

    status = setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &enableMulticast, sizeof(enableMulticast));

    socketAddr.sin_family = AF_INET;
    socketAddr.sin_port = htons(INT_PORT);
    socketAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    status = bind(socketfd, (struct sockaddr *)&socketAddr, sizeof(struct sockaddr_in));    

    status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
    if (status < 0)  cout << "connect error" <<endl ;

    cout << "Waiting to receive data..."  << endl;
    socklen = sizeof(struct socketAddr);

    while(1){
        status = recvfrom(socketfd, incomming_data_buffer, IN_LEN, 0, (struct sockaddr *)&socketAddr, &socklen);

        if(status >= 0) {
            cout << "data received" ;
            freeaddrinfo(host_info_list);
            close(socketfd);

            exit(0);
         }
    }     
}

【问题讨论】:

  • 我从来没有使用connect()来接收广播包。 connect() 的合理性是什么?
  • @harper 已记录在案。请参阅 man 页面。
  • 你能看到到达 Wireshark 的数据包吗?
  • “Wireshark”那是什么?

标签: c++ sockets udp recvfrom


【解决方案1】:
if(status = 0)

这不可能是真的。 (1) 这是status == 0 的错字; (2) 应该是status &gt;= 0,即status是接收到的数据报的长度。

【讨论】:

  • 我认为你可以忽略这一点。问题在于 recvfrom 函数。由于某种原因,它被绞死了。
  • 主要问题是recvfrom函数后程序没有前进。
猜你喜欢
  • 1970-01-01
  • 2016-09-26
  • 2013-05-22
  • 2018-01-03
  • 2015-05-23
  • 1970-01-01
  • 2014-08-12
  • 2014-05-11
  • 1970-01-01
相关资源
最近更新 更多