似乎无法将客户端地址保存到 sourceMsgs[j]

标签 c udp ip-address sendto sockaddr-in

标题说明了一切,这可能是一件简单的事情,但我在编程方面还很陌生,因此提出了一个愚蠢的问题..

我有:

printf("sourcemsg: %s", inet_ntoa(sourceMsgs[j].sin_addr));

查看 sourceMsgs[j] 中保存的 IP 地址是否正确,因此我假设问题出在:

nbytes = sendto(s, response , reslen, 0 , (struct sockaddr *)&sourceMsgs[i],sizeof(sourceMsgs));
            //    (uk: save the coordinates/address of the source of the received message
            //    in table sourceMsgs at index nReceivedMessages).

            //I'm pretty sure what I did here is wrong

            int j = nReceivedMessages;
            sourceMsgs[j].sin_addr = cli_addr.sin_addr;
            printf("sourcemsg: %s", inet_ntoa(sourceMsgs[j].sin_addr));
            nReceivedMessages++;
            total += receivedValue;

            printf("<Servidor> Valor recebido: %f\n", receivedValue);
            //(uk: <Server> Received value)

            if(nReceivedMessages == 1){


                timeout = 1;
                setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(DWORD));

            }

        }

    }

    sprintf(response,  "Received Messages: %f Total: %f", nReceivedMessages, total);

    int reslen = sizeof(response);

    for(i=0; i<nReceivedMessages; i++){

        //    (uk: transmit the content of variable response, the previously defined string, to
        //    all the destinations in table sourceMsgs).

        nbytes = sendto(s, response , reslen, 0 , (struct sockaddr *)&sourceMsgs[i],sizeof(sourceMsgs));

如果这篇文章非常不完整,我深表歉意,但这是我的第一篇文章。 感谢您提前提供的帮助

编辑:

看来问题确实在于传递结构的长度(WSAError 10014)。 现在的代码是这样的:

nbytes = sendto(s, response , strlen(response), 0 , (struct sockaddr *)&sourceMsgs[i].sin_addr, sizeof(sourceMsgs[i].sin_addr));

我不太确定该怎么做,但可能有不同的方法:

               sourceMsgs[j].sin_addr = cli_addr.sin_addr;
               printf("sourcemsg: %s", inet_ntoa(sourceMsgs[j].sin_addr));
               nReceivedMessages++;
               total += receivedValue;

因为我认为我的做法是搞砸了。

最佳答案

传递结构长度时可能存在问题。

nbytes = sendto(s, response, reslen, 0, (struct sockaddr *)&sourceMsgs[i], sizeof(sourceMsgs[i]));

// sizeof(sourceMsgs) gives - ( sizeof(sourceMsgs[1] or struct sockaddr_in) * (No. of messages in array) ).

此外,我注意到使用setsockopt 设置接收超时时出现问题。请参阅SO_RCVTIMEO进行解释。

关于似乎无法将客户端地址保存到 sourceMsgs[j],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58635447/

相关文章:

当 makefile 调用 GCC 时,C 程序不会在没有警告的情况下编译 - 否则可以工作

c++ - 将 UDP 数据包发送到同一地址的效率

java - 在 playframework 应用程序中查找 IP 地址

VMware 主机和 guest 之间的 Python UDP 和 TCP 通信无法正常工作

c++ - 如何打印MAC地址

php - HTML5 Websocket 仅适用于本地主机

java - Java 中 C 的 *char 的等价物是什么

javascript - 是否可以将 C 代码编译为 Javascript 代码?

c - 通过引用函数传递结构后访问结构指针

一台服务器中的 Java TCP 和 UDP 回显