从libpcap捕获中提取数据包长度

时间:2014-05-20 20:50:22

标签: c arrays integer libpcap

我正在使用libpcap(gcc,linux),出于某种原因,我想从u_char packet[]中提取数据包长度,将其保存为整数;说数据包长度存储在packet[38] packet[39]中。类似的东西:

#include <stdio.h>
#include <netdb.h>

int main(int argc, char *argv[]) {

u_char packet[2] = {0xaa, 0xfc};

int length = 0xaafc; // how to do that ?

printf("%d\n", length);
}
到目前为止,我已经尝试过这个:

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>


int main(void)
{
    u_char packet[2] = {0xaa, 0xfc};
    int l = packet[0] | (packet[1]<<8);
    printf("%d\n", l);
}

但没有成功!

那么如何在c中完成这个?如果我应该在这里发布整个代码,只需将其命名为......

感谢。

2 个答案:

答案 0 :(得分:1)

在执行左移之前你应该投射到int

int l = packet[0] | (((int)packet[1])<<8);

如果没有这个演员表,packet[1]<<8为0 - 你取8位变量并将其位移8次。你最终会得到8个零位。

答案 1 :(得分:0)

虽然您可以按照自己的方式进行操作,但将指针缓冲区转换为正确的类型要容易得多:

#include <linux/ip.h>

int main(void)
{
    u_char *packet = ...;
    int total_len;
    int ip_hdr_len;

    struct iphdr* iph;
    struct tcphdr* tcph;

    iph = (void*)packet;

    // Remember fields are in network order!
    // convert them to host order with ntoh[sl]
    total_len = ntohs(iph->tot_len);

    ip_hdr_len = iph->ihl * 4;

    // Assuming TCP...
    // Also be sure to check that packet is long enough!
    tcph = (void*)(packet + ip_hdr_len);
}
相关问题