struct ip和struct iphdr之间的区别

alb*_*ttx 6 c ip networking icmp

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

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

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

  • struct ip并且struct iphdr大小为20个字节
  • struct icmp 大小为28个字节
  • struct icmphdr 大小为8个字节

我猜这struct icmp包括一个struct ip/iphdr?

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

是否链接到IP_HDRINCL设置setsockopt()

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

ip和iphdr结构:

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. */
};
Run Code Online (Sandbox Code Playgroud)

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 */
};
Run Code Online (Sandbox Code Playgroud)

ICMP结构代码在这里:https://www.cymru.com/Documents/ip_icmp.h

dus*_*uff 11

struct ip并且struct iphdr是从不同地方引入的相同底层结构的两种不同定义.

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

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

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


struct icmp并且struct icmphdr是一个更混乱的情况:

  • <netinet/icmp.h>定义 struct icmpstruct icmphdr.
  • <linux/icmp.h>还定义struct icmphdr了具有类似结构(但通常是不同的字段名称)作为定义<netinet/icmp.h>.

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

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