简体   繁体   中英

Negative Numbers over TCP socket C

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.

The htonl / ntohl functions are specifically for unsigned 32-bit integers.

The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM