I am writing a bittorrent client in C++ that receives a message from a tracker (server) containing several 6 byte strings. The first 4 bytes represent the IP address of a peer and the next 2 bytes represent the port number that the peer is listening on.
I have worked out how to convert the ip bytes into a human readable ip address but am struggling to convert the two bytes representing the port number into an int (or something similar)
Here are my efforts so far:
BYTE portbinary[2];
unsigned short peerport;
//trackers[i]->peersBinary[j * 6 + 4] is the first byte
portbinary[0] = trackers[i]->peersBinary[j * 6 + 4];
//trackers[i]->peersBinary[j * 6 + 5] is the second byte
portbinary[1] = trackers[i]->peersBinary[j * 6 + 5];
peerport = *portbinary;
Upon examination peerport only seems to contain the integer representation of the first byte, how might I be able to fix this?
Thanks in advance 🙂
I prefer using bitwise operations instead of type punning because it brings no issues with endianness at all (the port number comes as a big endian number, and many systems today are little endian).