cudpip-addresssendtosockaddr-in

Can't seem to save the client's address to sourceMsgs[j]


The title says it all, it might be a simple thing but I'm pretty much new at programming hence the stupid question..

I have:

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

to see if the ip address that is saved in sourceMsgs[j] is the correct one and it was so I'm assuming the problem is at:

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));

I apologise if the post is extremely incomplete but it is my first one. Thank you for the help in advance

Edit:

It seems the problem is indeed with passing the length of the structure (WSAError 10014). The code is like this now:

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

I'm not really sure what to do, but there probably is a different way to do:

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

since I think the way I did it is a but screwed up.


Solution

  • There might be a problem with passing the length of the structure.

    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) ).
    

    Also, I noticed a problem setting recv timeout using setsockopt. See SO_RCVTIMEO for explanation.