0

我正在尝试使用libpcap. 这是我的代码:

int main (int argc, char **argv) {
    char *dev = "eth0";
    char errbuf[PCAP_BUFFER_SIZE];
    pcap_t *handle;

    char filter[] = "tcp and src port 80";
    struct bpf_program fp;
    bpf_u_int32 mask, net;

    handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
    pcap_compile(handle, &fp, filter,0,net);
    pcap_setfilter(handle, &fp);
    pcap_loop(handle, -1, got_packet, NULL);

    pcap_freecode(&fp);
    pcap_close(handle);

    return 0;
}

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
    static int count = 1;
    static int http_count = 1;
    const struct sniff_ethernet *ethernet;
    const struct sniff_ip *ip;
    const struct sniff_tcp *tcp;

    int size_ip;
    int size_tcp;
    int size_payload;

    count++;

    ethernet = (struct sniff_ethernet*) (packet);
    ip = (struct sniff_ip*) (packet + SIZE_ETHERNET);
    size_ip = IP_HL(ip)*4;
    if (size_ip  < 20){
        printf("Invalid IP header %d", size_ip);
        return;
    }

    if (ip->ip_p != IPPROTO_TCP){
        printf("Not TCP\n");
        return;
    }

    tcp = (struct sniff_tcp*) (packet +SIZE_ETHERNET+size_ip);
    size_tcp = TH_OFF(tcp) * 4;
    if (size_tcp < 20) {
        printf("Invalid TCP header");
        return;
    }

    if ((tcp->th_flags & TH_ACK) != 0) {
        const char *payload = (const char *) (packet + SIZE_ETHERNET + size_ip + size_tcp);
        size_payload = ntohs(ip->ip_len)- (size_ip + size_tcp);
        std::cout << payload << "\n";       
        if (count == 4)
            exit(0);
    }

参数是:

#define SNAP_LEN    65535
#define SIZE_ETHERNET   14
#define ETHER_ADDR_LEN  6
#define PCAP_BUFFER_SIZE 65535

现在,整个第四个数据包都没有打印出来。我使用转储了数据包tcpdump,它得到了整个数据包,但我的代码没有。这里有什么问题吗?

4

1 回答 1

0

原来这是打印的问题。我使用了该功能print_payload,现在可以正常工作。

于 2012-09-29T01:39:35.920 回答