Error comparing socket addresses

I am currently working on a UDP application that allows two users to talk to each other using the winsock library. Currently, when my program starts, it first stores the sockaddress into a vector and then when the user posts a message, it compares the address to the first address in the vector. When I debug and compare the compared values ​​they are exactly the same, but mine is if the statment goes to else (it thinks the addresses are not equal to each other)

this is the code i have:

#include <WinSock2.h>

sockaddr    clientAddress;

recvfrom( hSocket, msg, MAXLINE, 0, &clientAddress, &cbClientAddress );

myVector.pushback(clientAddress);

if (&clientAddresses[0] == &clientAddress)
{
//is the same address
}
else
{
//not the same address
}

      

I've also tried to be more specific using .sa_data

after clientAddress[0]

and&clientAddress.

thank

+3


source to share


1 answer


Several problems:



  • Before calling recvfrom

    you need to initialize cbClientAddress

    (type socklen_t

    ) to the number of bytes of address information you are willing to accept, for example:

     struct sockaddr clientAddress;
     socklen_t cbClientAddress;
    
     cbClientAddress = sizeof(clientAddress);
     recvfrom(hSocket, msg, MAXLINE, 0, &clientAddress, &cbClientAddress);
    
          

  • After the call, the cbClientAddress

    actual length of the received address will be overwritten. It will be smaller sizeof(struct sockaddr)

    . In fact it will be equal sizeof(struct sockaddr_in)

    because it is a UDP / IP socket.

  • You should only compare the part of the structure that actually contains the data, not the entire structure. The unused portion of the structure (size difference between struct sockaddr_in

    and struct sockaddr

    ) can be garbage. You don't want to compare it. This will require not only memorizing the contents of the structure itself in the vector, but also a considerable length.

  • When comparing the saved address with the one you just got, use this pseudocode. Don't try to compare the entire structure (including trailing unused parts).

    if (
        (saved_length == this_length) &&
        (memcmp(saved_sockaddr, this_sockaddr, this_length) == 0)
    ) {
        it a match
    }
    
          

  • Your code is &clientAddresses[0] == &clientAddress

    checking if the addresses of the structures are equal. This means that you are testing to make sure it is the same structure and not what you want, which is testing if it is a structure with the same content. Use memcmp

    as per the above pseudocode to compare content.

+1


source







All Articles