0

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

我有:

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;

因为我认为我这样做的方式是搞砸了。

4

2 回答 2

0

to 的参数sendto应该是指向sockaddr结构的指针,而不是包含它的结构。

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

于 2019-10-31T00:50:53.917 回答
0

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

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

于 2019-10-31T04:13:36.367 回答