libpcap - packet ip header length是带有loopback tcp请求的零字节

Nic*_*ick 1 c network-programming tcp libpcap

我试图使用libpcap查看TCP有效负载信息.为此,我需要在内存中找到有效负载的位置.我正在使用这个Programming With Pcap指南来确定请求有效负载的位置.嗅探源自与服务(环回适配器)位于同一台机器上的客户端的数据包时,IP标头长度为0.我无法成功找到请求有效负载的位置.听循环适配器时会出现这种情况吗?我正在使用MacOSx 10.8系统监听适配器'lo0'.

这是我正在尝试的:

    //this callback is called when a packet is found
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet){
    ethernet = (struct sniff_ethernet*)(packet);
    ip = (struct sniff_ip*)(packet + SIZE_ETHERNET); <-- the result is 0
    size_ip = IP_HL(ip)*4;
    if (size_ip < 20) {
        printf("   * Invalid IP header length: %u bytes\n", size_ip);
        return;
    }
    tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
    size_tcp = TH_OFF(tcp)*4;
    if (size_tcp < 20) {
        printf("   * Invalid TCP header length: %u bytes\n", size_tcp);
        return;
    }
    payload = (u_char *)(packet + SIZE_ETHERNET + size_ip + size_tcp);

}
Run Code Online (Sandbox Code Playgroud)

struct sniff_ip:

#define SIZE_ETHERNET 14

 /* IP header */
struct sniff_ip {
    u_char ip_vhl;      /* version << 4 | header length >> 2 */
    u_char 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_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)

小智 8

ethernet = (struct sniff_ethernet*)(packet);
ip = (struct sniff_ip*)(packet + SIZE_ETHERNET); <-- the result is 0
Run Code Online (Sandbox Code Playgroud)

如果你在loopback接口上捕获,那么代码是错误的.OS X(或任何其他支持libpcap/WinPcap的操作系统)上的所有接口都不提供以太网头; 您需要调用pcap_datalink()以查找捕获设备的链接层类型(或捕获文件,如果您正在读取捕获文件pcap_open_offline()),并在此基础上解析数据包的链路层标头.

有关完整列表,请参阅pcap链路层标头类型列表.

DLT_EN10MB是以太网设备的链路层标头类型("10MB"是历史性的,指的是3MB与10MB以太网,它们具有不同的标头; DLT_EN10MB适用于10 MB和100 MB以及1 GB和10 GB以及40 GB和100 GB和......以太网),以及一些提供虚假以太网报头的非以太网设备.

大多数BSD和OS X上的环回设备的链路层头类型是DLT_NULL; 如链接层头类型页面所示,它有一个4字节的链路层头,其中包含PF_协议的操作系统值,可能是IPv4或IPv6.