ネットワークプログラミングにおけるバイトシーケンス変換(linux下)


一、バイトシーケンス変換
#include
uint16_t  htons(uint16_t   hostshort);
機能:unsigned shortタイプのデータのホストバイト順をネットワークバイト順に変換します.
戻り値:変換後のバイトシーケンスが正常に返されました.
 
次に例を示します.
#include <stdio.h>

int main(void)
{
        unsigned int i ,num=0xab127980;
        unsigned char * pc;

        printf("nums address is %p , and it's value is 0x%x

",&num,num); pc = (unsigned char *)&num; for(i = 0 ; i < 4 ; i++) { printf("%p:0x%x

",pc,(unsigned int)*pc); pc++; } unsigned short port; port = 0x6789; printf("port number in host byteorder is 0x%x
",port); printf("port number in network byteorder is 0x%x
",htons(port)); }

実行結果:
[root@rac2 ~]# ./byteorder 
nums address is 0xbfe78be0 , and it's value is 0xab127980

0xbfe78be0:0x80

0xbfe78be1:0x79

0xbfe78be2:0x12

0xbfe78be3:0xab

port number in host byteorder is 0x6789
port number in network byteorder is 0x8967

 
このことから,本機では小端システム,すなわち整数の地位をメモリの低アドレスに,整数の高位をメモリの高アドレスに置く.
各PC機の内部対スカラーのバイト格納順序が異なるため.一方、ネットワークデータ交換では、ネットワークで伝送されるデータフォーマットは、ネットワークバイトフォーマット、すなわち大端バイトシーケンスでなければならない.そのため、フォーマットを変換する必要があります.