I am currently working on a UDP application that allows two users to talk to eachother using the winsock librarary. Currently when my program runs, it first saves the sockaddress to a vector and then when the user sends a message it compares the address to the first address in the vector. When I debug and compare the values being compared they are exactly the same yet my if statment goes to the else (it thinks that the addresses dont equal 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
}
Ive also tried being more specific with using .sa_data after the clientAddress[0] and &clientAddress.
Thanks
Multiple issues:
Before the call to
recvfrom, you need to initializecbClientAddress(of typesocklen_t) to the number of bytes of address information you are ready to receive, like this:After the call,
cbClientAddresswill be overwritten with the actual length of the address that was received. This will be shorter thansizeof(struct sockaddr). In fact it will be equal tosizeof(struct sockaddr_in)because this is a UDP/IP socket.You must compare only the part of the structure that actually contains data, not the whole structure. The unused portion of the structure (the difference in size between
struct sockaddr_inandstruct sockaddr) might be garbage. You don’t want to compare it. This will necessitate not only memorizing the contents of the structure itself in a vector, but also the significant length.When comparing the saved address against the one you’ve just received, use this kind of pseudocode. Don’t try to compare the whole structure (including trailing unused portions).
Your code
&clientAddresses[0] == &clientAddresschecks if the addresses of the structures are equal. This means you’re testing to see if it’s the same structure instead of what you want, which is testing if it’s a structure with the same contents. Usememcmpas per the pseudocode above to compare the contents.