Chinaunix首页 | 论坛 | 博客
  • 博客访问: 584592
  • 博文数量: 92
  • 博客积分: 5026
  • 博客等级: 大校
  • 技术积分: 1321
  • 用 户 组: 普通用户
  • 注册时间: 2008-02-28 11:04
文章分类

全部博文(92)

文章存档

2011年(9)

2010年(17)

2009年(12)

2008年(54)

我的朋友

分类: LINUX

2008-07-30 14:44:21

大端字节和小端字节顺序.
网络编程的时候会常用到,也是挺简单的.不过今天看到netinet/ip.h
 

struct ip
  {
#if __BYTE_ORDER == __LITTLE_ENDIAN
    unsigned int ip_hl:4; /* header length */
    unsigned int ip_v:4; /* version */
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
    unsigned int ip_v:4; /* version */
    unsigned int ip_hl:4; /* header length */
#endif
    u_int8_t ip_tos; /* type of service */
    u_short ip_len; /* total length */
    u_short ip_id; /* identification */
    u_short ip_off; /* fragment offset field */
#define IP_RF 0x8000 /* reserved fragment flag */
#define IP_DF 0x4000 /* dont fragment flag */
#define IP_MF 0x2000 /* more fragments flag */
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
    u_int8_t ip_ttl; /* time to live */
    u_int8_t ip_p; /* protocol */
    u_short ip_sum; /* checksum */
    struct in_addr ip_src, ip_dst; /* source and dest address */
  };

前两个字段ip_v和ip_hl在包结构里头是顺序定义的,但是每个占了4位,所以又涉及到了字节顺序的问题了.每个ip结构定义出来,到最后始终会变成一段位序列放到网络上进行传输.

现在ipv4头长度5(20字节)的位序列应该是0100 0101 ... 所以大端格式应该先分配0100 然后分配0101(大端格式总是从高位开始分配的).小端格式应该先分配0101然后再分配0100(小端格式总是从地位开始分配的).所以大端和小端格式的机器定义包结构也不同的.可以假设一下错误的分配方法就能看出来了

虽然解释的不清楚,但总算知道该怎么样的!

阅读(1890) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~