struct ip和struct iphdr

时间:2017-03-16 17:13:07

标签: c networking ip icmp

我试图了解网络是如何工作的,我正在做一些测试,发送一些软件包......无论如何

我的观点是,我找不到"protocol" structure"protocol header" structure之间的真正区别。

对于ip结构,它们都大小为20个字节。 但例如:

  • struct ipstruct iphdr大小为20个字节
  • struct icmp大小为28字节
  • struct icmphdr大小为8个字节

我猜测struct icmp包含struct ip/iphdr?

我所看到的每个协议都有相同的结构。 struct udp / struct udphdr

是否与IP_HDRINCL设置了setsockopt()

所以我的问题是它们之间真正的区别是什么?当使用好的时候。

ip和iphdr struct:

struct iphdr {
    #if defined(__LITTLE_ENDIAN_BITFIELD)
        __u8    ihl:4,
                version:4;
    #elif defined (__BIG_ENDIAN_BITFIELD)
        __u8    version:4,
                ihl:4;
    #else
        #error  "Please fix <asm/byteorder.h>"
    #endif
         __u8   tos;
         __u16  tot_len;
         __u16  id;
         __u16  frag_off;
         __u8   ttl;
         __u8   protocol;
         __u16  check;
         __u32  saddr;
         __u32  daddr;
         /*The options start here. */
};

IP HDR

struct ip {
#if BYTE_ORDER == LITTLE_ENDIAN 
    u_char  ip_hl:4,        /* header length */
        ip_v:4;         /* version */
#endif
#if BYTE_ORDER == BIG_ENDIAN 
    u_char  ip_v:4,         /* version */
        ip_hl:4;        /* header length */
#endif
    u_char  ip_tos;         /* type of service */
    short   ip_len;         /* total length */
    u_short ip_id;          /* identification */
    short   ip_off;         /* fragment offset field */
#define IP_DF 0x4000            /* dont fragment flag */
#define IP_MF 0x2000            /* more fragments flag */
    u_char  ip_ttl;         /* time to live */
    u_char  ip_p;           /* protocol */
    u_short ip_sum;         /* checksum */
    struct  in_addr ip_src,ip_dst;  /* source and dest address */
};

此处的ICMP结构代码:https://www.cymru.com/Documents/ip_icmp.h

1 个答案:

答案 0 :(得分:10)

struct ipstruct iphdr是相同底层结构的两种不同定义,从不同的地方引入。

struct ip<netinet/ip.h>中定义,它是UNIX系统上合理标准的标头。

struct iphdr<linux/ip.h>中定义。此标头(和结构)是特定于Linux的,不会出现在其他操作系统中。

如果您不确定要使用哪一个,请使用struct ip;使用此结构的代码更有可能移植到非Linux系统。

struct icmpstruct icmphdr情况比较混乱:

  • <netinet/icmp.h>定义 struct icmpstruct icmphdr
  • <linux/icmp.h>还定义了struct icmphdr,其结构与<netinet/icmp.h>中的定义类似(但通常是不同的字段名称)。

第一:除非你有充分的理由,否则不要包括<linux/icmp.h>。你不能包含两个标题 - 它们会发生冲突 - 并且大多数软件都会期望netinet定义。

第二:struct icmphdr顾名思义就是标题。 struct icmp定义结构化ICMP消息的内容,如目标不可达消息。

相关问题