I am new to socket programming and I am trying to understand the operation of htons()
. I\'ve read a few tutorials on the Internet like this and this one for in
It is done to maintain the arrangement of bytes which is sent in the network(Endianness). Depending upon architecture of your device,data can be arranged in the memory either in the big endian format or little endian format. In networking, we call the representation of byte order as network byte order and in our host, it is called host byte order. All network byte order is in big endian format.If your host's memory computer architecture is in little endian format,htons() function become necessity but in case of big endian format memory architecture,it is not necessary.You can find endianness of your computer programmatically too in the following way:->
int x = 1;
if (*(char *)&x){
cout<<"Little Endian"<
and then decide whether to use htons() or not.But in order to avoid the above line,we always write htons() although it does no changes for Big Endian based memory architecture.