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

问题描述 投票:0回答:2

标题说明了一切,这可能很简单,但是我在编程上是新手,因此是个愚蠢的问题。

我有:

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 tam = sizeof(cli_addr);
            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));

我很抱歉,如果该帖子非常不完整,但这是我的第一篇。谢谢您的事先帮助

c udp ip-address sendto sockaddr-in
2个回答
0
投票

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

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


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设置recv超时时出现问题。有关说明,请参见SO_RCVTIMEO

© www.soinside.com 2019 - 2024. All rights reserved.