首页 > 解决方案 > recvfrom 非阻塞返回 C++ 中的 BAD ADDRESS 错误

问题描述

我在尝试收听而不是发送时收到“BAD ADDRESS”错误。发送与 sendto() 完美配合。

这是创建要侦听的套接字的函数。IP 和端口是本地的(这是为了在同一个本地网络中执行,实际上是在使用 linux 虚拟机和 windows 机器的同一台 pc 中)。

在 getaddrinfo(NULL, port, &hints, &addrInfoResults); 中使用 NULL 似乎要走的路:不知道为什么使用发件人的本地 IP(例如 192.168.1.50)不起作用。但发送工作。

    int socketDescriptor;
    sockaddr socketAddress;

    struct addrinfo hints;
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_INET; // Allow only IPv4
    hints.ai_socktype = SOCK_DGRAM; // Datagram socket, type of packages used in UDP
    hints.ai_protocol = IPPROTO_UDP; // UDP protocol
    hints.ai_flags = AI_PASSIVE; // USE MY IP


    // resolve dynamically IP adress by getaddrinfo()
    struct addrinfo *addrInfoResults;
    int resVal = getaddrinfo(ip, port, &hints, &addrInfoResults);
    if (resVal != 0) {
        // ERROR
        return false;
    }

    struct addrinfo *addInf;
    for(addInf = addrInfoResults;addInf != NULL; addInf = addInf->ai_next) {
        if (addInf->ai_family == AF_INET) { // IPv4
            struct sockaddr_in *ipv4 = (struct sockaddr_in *)addInf->ai_addr;
            void *addr = &(ipv4->sin_addr);

            // convert the IP to a string
            char ipstr[16]; // IPv4 is 16
            inet_ntop(addInf->ai_family, addr, ipstr, sizeof ipstr);
            break;
        }
    }

    // Create connection with socket
    socketDescriptor = 0;
    if ( (socketDescriptor = socket(addInf->ai_family, addInf->ai_socktype, addInf->ai_protocol)) == -1)
    {
        // ERROR...
        return false;
    }

    // Try to bind to that address
    if (bind(socketDescriptor, addInf->ai_addr, addInf->ai_addrlen) == -1)
    {
        // ERROR
        return false;
    }

    socketAddress = *(addInf->ai_addr);
    freeaddrinfo(addrInfoResults);

    // Set socket non blocking
    fcntl(socketDescriptor, F_SETFL, O_NONBLOCK);

连接时,任何呼叫均未收到错误消息。套接字已创建。接听电话是这个:

    socklen_t addrSize = sizeof(socketAddress);
    int numbytes = recvfrom(socketDescriptor,
                        buffer,
                        sizeof(bufferStruct),
                        0,
                        &socketAddress,
                        &addrSize);

    if (numbytes < 0)
    {

        int errnoBackup = errno;
        if (errnoBackup != EWOULDBLOCK && errnoBackup != EAGAIN)
        {
            _logFile << "ERROR" << std::endl;
            ....

为什么我收到 BAD Address 错误?我已阅读与此相关的所有帖子,但没有任何帮助。我总是收到-1。

到目前为止我所做的测试:

标签: c++socketserrnoberkeley-sockets

解决方案


只是为了让大家知道这件事。如果您有 BAD ADDRESS,如 IBM 文档所述:

调用 recvfrom 时:缓冲区(指向 NULL)、地址(指向错误的位置,或者您没有传递对实际位置的引用而不是指针)或地址的大小(即你没有正确计算它)。

我的问题是我没有初始化缓冲区。


推荐阅读