zoukankan      html  css  js  c++  java
  • 判断主机、网络字节序和互相转换

    大端字节序(big-endian):按照内存地址的增长方向,高位数据储存于低位地址。

    小端字节序(little-endian):按照内存地址增长方向,高位数据储存于高位地址。

    判断主机、网络字节序:

    #include <stdio.h>
    #include <arpa/inet.h> int main(void) {   unsigned short int h = 0x1234;   unsigned short int n;
      
    if (*((unsigned char *)&h) == 0x12) {     printf("big-endian ");   }   if (*((unsigned char *)&h) == 0x34) {     printf("little-endian ");   }
      n = htons(h);
      if (*((unsigned char *)&n) == 0x12) {
        printf("big-endian ");
      } else {
        printf("little-endian ");
      } 
      
    return 0; }

    或者:

    #include <stdio.h>  
    #include <arpa/inet.h>  
      
    int main(){  
        unsigned long a = 0x12345678;  
        unsigned char *p = (unsigned char *)(&a);  
        printf("主机字节序:%0x    %0x   %0x   %0x
    ",  p[0], p[1], p[2], p[3]);  
    
        unsigned long b = htonl(a);  //将主机字节序转化成了网络字节序  
                      
        p = (unsigned char *)(&b);  
      
        printf("网络字节序:%0x    %0x   %0x   %0x
    ",  p[0], p[1], p[2], p[3]);  
        
      return 0; }
    结果:
      主机字节序:78 56 34 12
      网络字节序:12 34 56 78

    转化:

    include <stdio.h>  
    #include <arpa/inet.h>  
    
    int main()  
    {  
        struct in_addr ipaddr;  
        unsigned long addr = inet_addr("192.168.1.100");  
        printf("addr = %u
    ", ntohl(addr));  
    
        ipaddr.s_addr = addr;  
        printf("%s
    ", inet_ntoa(ipaddr));    
        return 0;    
    } 
    结果:
      addr = 3232235876
      129.168.1.100

     参考:http://blog.csdn.net/msdnwolaile/article/details/50727653

    主机字节序与网络字节序的转换函数:htonl、ntohl、htons、ntohs     网址:http://blog.csdn.net/kulala082/article/details/53431473

  • 相关阅读:
    使用jQuery修改动态修改超链接
    360安全检测出的WordPress漏洞的修复方法
    jQuery未定义错误原因(jQuery is not define)
    MySQL授权命令grant的使用方法
    .htaccess伪静态(URL重写)绑定域名到子目录实现子站点
    Ubuntu14.04配置3389远程桌面连接
    [20190531]ORA-600 kokasgi1故障模拟与恢复.txt
    [20190531]建立job与commit.txt
    [20190530]ORACLE 18c
    [20190530]oracle Audit文件管理.txt
  • 原文地址:https://www.cnblogs.com/coolYuan/p/8350727.html
Copyright © 2011-2022 走看看