Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and how to use C++ htonl function

Tags:

c++

htonl

cout << "Hello World !" << endl;

For my very first post on stackoverflow: When are we supposed to use the htonl function? I have gone through the man page. However, I don't really understand when and how to use it.

like image 405
json27 Avatar asked May 22 '15 00:05

json27


People also ask

Why do we use Htonl in C?

The htonl function can be used to convert an IPv4 address in host byte order to the IPv4 address in network byte order.

What is the purpose of using Htonl and Htons functions in network programming using C ++?

Function description: The function htonl converts an integer number from the byte order accepted on the computer into the network byte order. The function htons converts an integer short number from the byte order accepted on the computer into the network byte order.

What does Htonl stand for?

Host to network and network to host are actually the same thing and really should be called 'change endianness if this is a little endian machine' So on a little endian machine you do net, ie be, number = htonl / ntohl (le number) and send the be number on the wire.

Why is Htons used?

The htons function can be used to convert an IP port number in host byte order to the IP port number in network byte order.


1 Answers

Host TO Network translation. It makes sure the endian of a 32 bit data value is correct (Big endian) for network transport. ntohl -- Network TO Host -- is used by the receiver to ensure that the endian is correct for the receiver's CPU. Keep an eye out for htons and ntohs for handling 16 bits, and out there somewhere are likely htonll and ntohll for 64 bits.

Using all of them is as simple as pass in the number you want converted and out comes the converted number. You may find that absolutely nothing has happened on some processors because their endian is already big.

uint32_t inval = 0xAABBCCDD;
uint32_t outval = htonl(inval);

Will, on most desktop hardware, result in outval being set to 0xDDCCBBAA

like image 72
user4581301 Avatar answered Oct 04 '22 17:10

user4581301