jcalfee314
jcalfee314

Reputation: 4830

converting 4 socket bytes to an int

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;

Upvotes: 3

Views: 1099

Answers (2)

Robert Martin
Robert Martin

Reputation: 17157

Ignoring the obvious error that you are calling return in a void function...

The recv function, 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 to cout the buffer, not the # of bytes read.

However, printing an int will print the entire thing.. not byte-by-byte like you're expecting. What about something like this?

int nb, i;
union {
     uint32_t whole;
     char bytes[4];
} v;
nb = recv(hSocket, v.bytes, 4, MSG_WAITALL);
if (nb != 4)
    printf("Error: recv returned: %d\n", nb);
else
    printf("%d %d %d %d\n", v.bytes[0], v.bytes[1], v.bytes[2], v.bytes[3]);

First, you should make sure you're seeing "130 0 0 0" or "0 0 0 130" from the above example.

Now, try adding:

printf("%u\n", v.whole);

And see if you get 130. If you do, great. If you instead get 2 181 038 080 or -33 554 432it means your bytes are in the wrong order (google 'endianness'). You can fix this with a byte-reordering command:

v.whole = ntohl(v.whole);
printf("%u\n", v.whole);

ntohl re-orders the bytes to make the endianness match your local computer.

Upvotes: 5

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

The code is flawed. The function is declared not to return a value, yet it does.

recv returns the number of bytes read, so it would print 4, and the integer read will be stored in m_iVersion. Whether the integer contains 130 or a high number depends on the endianness of the computer.

Upvotes: 2

Related Questions