The code below is reading 4 bytes from a socket into an integer. I can see the bytes are (in decimal) 130 0 0 0. I suspect the code below will return version 130 but I don’t know why. Will this return 130? I attempted to replicate it in Java but I a very large negative number (more to what I would expect). How do I interpret pseudo/C code below?
#include <socket.h>
void readVersion(char *buf, int iCount) {
recv(hSocket, buf, iCount, MSG_WAITALL);
}
int m_iVersion;
readVersion((char *) &m_iVersion, sizeof (m_iVersion))
count << m_iVersion;
Ignoring the obvious error that you are calling
returnin avoidfunction…The
recvfunction, by definition, returns an integer telling you the number of bytes read (or negative if error). If you want to read the bytes and return them, you want tocoutthe buffer, not the # of bytes read.However, printing an
intwill print the entire thing.. not byte-by-byte like you’re expecting. What about something like this?First, you should make sure you’re seeing “130 0 0 0” or “0 0 0 130” from the above example.
Now, try adding:
And see if you get 130. If you do, great. If you instead get
2 181 038 080or-33 554 432it means your bytes are in the wrong order (google ‘endianness’). You can fix this with a byte-reordering command:ntohlre-orders the bytes to make the endianness match your local computer.