htons() function in socket programing

前端 未结 4 607
执笔经年
执笔经年 2020-12-22 19:06

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

4条回答
  •  囚心锁ツ
    2020-12-22 19:19

    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.

提交回复
热议问题