Whenever I try to send a negative number over a TCP socket, when I print what was received,it reads “4.29497e+09”. All I’m doing is this:
int i = -8;
int temp = htonl(i);
write(sock,&temp,4);
On the Server:
int temp;
read(sock, &temp,4);
int read = ntohl(temp);
cout << read << endl;
If anyone could help, it would be much appreciated.
When transferring data over a socket, you don’t need to convert it to network endianess.
This function is used to translate addresses, not actual data. These functions work with unsigned integers, so they don’t match your argument (signed integer)
You need to omit them.
If the second machine uses different endianess, which is kind of rare (both 8086 and ARM architectures work with little endian), you need to swap the bytes when reading ints and shorts.
This is usually done on the receiving socket.