How can a int16_t be transmitted safely on C++ TCP socket? In the following code, the server doesn't seem to receive the correct values and my guess is it's because htonl/ntohl are not defined for int16_t.
Client:
void client(int16_t value, int socket) {
int16_t _value = htonl(value);
write(socket, _value, sizeof(int16_t));
}
Server:
int16_t server(int16_t buf, int16_t value, int socket) {
recv(socket,&buf,sizeof(int16_t));
value = ntohl(buf);
return value;
}
You are using the Long versions
ntohl()
andhtonl()
when you should be using the Short versionsntohs()
andhtons()
.Pro tip: make sure you check the return value of write() and recv() (and consider using write() with read() or send() with recv() as those are the more usual pairings).