網絡字節序,主機字節序,地址轉換函數

 

#include "../apue.h"

int main(void){

//驗證當前平臺屬哪種字節序

    unsigned int x=0x12345678;

    unsigned char *p=(unsigned char*)&x;

    printf("%x-%x-%x-%x\n", p[0],p[1],p[2],p[3]);

 

//將主機字節序轉換爲網絡字節序

    unsigned int y = htonl(x);

    p=(unsigned char*)&y;

    printf("%x-%x-%x-%x\n", p[0],p[1],p[2],p[3]);

 

//將IP轉換爲字節序整數

    in_addr_t ipm=inet_addr("192.168.0.100");

    printf("imp=%u\n", ntohl(ipm));

 

//將網絡字節序整數轉換成IP

    struct in_addr ipaddr;

    ipaddr.s_addr = ipm;

    printf("ip=%s\n", inet_ntoa(ipaddr));

 

//將IP轉換爲字節序整數

    struct in_addr inp={0};

    inet_aton("192.168.0.100", &inp);

    printf("inp=%u\n", ntohl(inp.s_addr));

    return 0;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章