User`s guide
KwikNet Overview
K
A
DAK
15
Net Endian Data
KwikNet provides a set of macros (or functions) which can be used by applications to
convert 2-byte (short) values and 4-byte (long) values between net endian form and host
endian form. These macros assume the host endianness defined in the KwikNet Network
Parameter File.
The following macros are available in the KwikNet Library.
nlv = htonl(hlv) Convert long from host to network endian form
nsv = htons(hsv) Convert short from host to network endian form
hlv = ntohl(nlv) Convert long from network to host endian form
hsv = ntohs(nsv) Convert short from network to host endian form
On big endian machines, these macros leave the data parameter unaltered since the
network is also big endian. On little endian machines, these macros reverse the order of
the bytes in the macro parameter.
It should be obvious that htonl and ntohl are equivalent as are htons and ntohs. So
which macro should be used if two are identical? Although it does not matter, it is
recommended that the macro be chosen for best meaning in the context of its use. For
example, when storing a long value hlv into memory for delivery in the data stream, use
htonl(hlv) to indicate the conversion of the data from host to net endian form.
Similarly, when fetching a long value hlv from a received data packet, use ntohl(nlv)
to indicate the conversion of the data from net to host endian form.
So how does your application know which data values require conversion? There is no
simple answer. The content of the data portion of any packet delivered on the network is
known only to the sender and receiver. Both must agree to the method of interpretation.
Of greater concern is the management of the data while it is under the control of your
application. Most hosts prefer to operate with data in the natural form dictated by the
target processor. For this reason, data is usually converted to net endian form prior to
sending and from net endian form upon receipt.
There are several data values which applications frequently use which, by convention, are
always maintained in net endian form. These are network parameters such as IP
addresses, subnet masks and default gateway addresses. It is good programming practice
to always use comments to identify variables which are assumed to be kept in net endian
form. All other variables can then safely be assumed to be in host endian form.