How to send int16_t over TCP socket?

407 views Asked by At

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;
}
1

There are 1 answers

0
John Zwinck On BEST ANSWER

You are using the Long versions ntohl() and htonl() when you should be using the Short versions ntohs() and htons().

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).