千家信息网

网络序,主机序学习

发表于:2025-12-01 作者:千家信息网编辑
千家信息网最后更新 2025年12月01日,网络序,主机序学习网络序,主机序总是迷迷糊糊的。需要整理一下。千言万语,不如代码来的实在。哈哈,说干就干。#include #include #include int host_order() {
千家信息网最后更新 2025年12月01日网络序,主机序学习

网络序,主机序学习

网络序,主机序总是迷迷糊糊的。需要整理一下。
千言万语,不如代码来的实在。哈哈,说干就干。

#include #include #include 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.100192     168  1  100 : inet_addr 192.168.1.10064      1 a8    c0 : inet_addr ntohl 192.168.1.100100     1  168  192 : inet_addr ntohl 192.168.1.100addr_host = 3232235876

清晰明了。有助于快速理解。

0