網絡序,主機序學習

網絡序,主機序學習

網絡序,主機序總是迷迷糊糊的。需要整理一下。
千言萬語,不如代碼來的實在。哈哈,說幹就幹。

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>

int host_order() 
{
    unsigned long a = 0x12345678;
    unsigned char * p = (unsigned char *)(&a);

    printf("主機字節序:%0x  %0x %0x %0x\n",p[0],p[1],p[2],p[3]);

    unsigned long b = htonl(a);

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

    printf("網絡字節序:%0x  %0x %0x %0x\n",p[0],p[1],p[2],p[3]);

    return 0;
}

int net_order()
{
    struct in_addr ipaddr;
    unsigned long addr = inet_addr("192.168.1.100");
    unsigned char *p = (unsigned char *)(&addr);
    printf("addr = %u \n",addr);
    printf("%0x %0x %0x %0x : inet_addr 192.168.1.100\n",p[0],p[1],p[2],p[3]);
    printf("%d  %d  %d  %d : inet_addr 192.168.1.100\n",p[0],p[1],p[2],p[3]);
    unsigned long addr_host = ntohl(addr);
    p = (unsigned char *)(&addr_host);
    printf("%0x %0x %0x %0x : inet_addr ntohl 192.168.1.100\n",p[0],p[1],p[2],p[3]);
    printf("%d  %d  %d  %d : inet_addr ntohl 192.168.1.100\n",p[0],p[1],p[2],p[3]);
    printf("addr_host = %u\n",addr_host);
    return 0;
}

int main()
{
    int ret = 0;
    //ret = host_order();
    ret = net_order();
    return ret ;
}

編譯之。

gcc -g  -o test_order test_order.c

跑一下。

[root@localhost test]# ./test_order                       
addr = 1677830336 
c0      a8 1    64 : inet_addr 192.168.1.100
192     168  1  100 : inet_addr 192.168.1.100
64      1 a8    c0 : inet_addr ntohl 192.168.1.100
100     1  168  192 : inet_addr ntohl 192.168.1.100
addr_host = 3232235876

清晰明瞭。有助於快速理解。

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