Reputation: 233
I am writing server and client and i have some integers to pass.
In my server application i am recieving an integer from the client.
In the client do i call ntohl or htonl on the integer? If i call either one of these, when i recieve the integer do i have to call ntohl or htonl again? Or do i only call ntohl/htonl on the server side, but not the client side?
In other words, when/where and how many times do i use htonl or ntohl for each integer?
Also, do i have to do ntohl/htonl for strings/chars arrays? Does chars have to be converted?
Upvotes: 0
Views: 822
Reputation: 310980
In the client do i call ntohl or htonl on the integer?
It has nothing to do with whether you are the client or the server. It has to do with whether you are sending or receiving. If you are sending, you want network byte order, so you call htonl
(). If you are receiving, you want host order, so you call ntohl().
If i call either one of these, when i recieve the integer do i have to call ntohl or htonl again?
Yes. The sender should have put the data into network byte order; the receiver has to put it into host order, for his local host.
In other words, when/where and how many times do i use htonl or ntohl for each integer?
htonl()
when sending; ntohl()
when receiving.
Upvotes: 1
Reputation: 597111
When sending an integer, always call hton...()
to make sure the bytes are converted from the sending machine's native byte order into network byte order.
When reading an integer, always call ntoh...()
to make sure the bytes are converted from network byte order into the receiving machine's native byte order.
On machine's where the native byte order is the same as network byte order, the functions are implemented as no-ops. On machine's where the native byte order is not the same, the functions perform byte swaps.
Upvotes: 1
Reputation: 4048
The typical setup in this scenario would be to call htonl
in the client (because you want to put the integer into network i.e. protocol order) and ntohl
in the server (because you want to convert back from network to host order).
There is no equivalent of ntohl
etc for strings (although you do have to make arrangements for the client and server to agree on the character encoding used, i.e. by having both sides use UTF-8).
Upvotes: 0