主机字节序和网络字节序

一、网络字节序

  网际协议使用大端字节序来传送多字节整数

二、确定主机字节序

#include <stdio.h>

int main(int argc, char **argv) {
    union {
        short s;
        char c[sizeof(short)];
    };
    un.s = 0x0102;
    if (sizeof(short) == 2) {
        if (un.c[0] == 1 && un.c[1] == 2) {
            printf("big-endian
");
        } else if (un.c[0] == 2 && un.c[1] == 1) {
            printf("little-endian
");
        } else {
            printf("unknow
");
        }
    } else {
        printf("sizeof(short) = %d
", sizeof(short));
    }
   exit(0); }

三、主机字节序和网络字节序的转换

#include <netinet/in.h>
uint16_t htons(uint16_t host16bitvalue); uint32_t htons(uint32_t host32bitvalue);
均返回:网络字节序的值
uint16_t ntohs(uint16_t net16bitvalue); uint32_t ntohl(uint32_t net32bitvalue);
均返回:主机字节序的值

注:h代表host,n代表network,s代表short,l代表long

 

原文地址:https://www.cnblogs.com/soldierback/p/10663300.html