2012-09-29 100 views
0

我试图用libpcap捕获数据包。这里是我的代码: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转储了数据包,它得到了整个数据包,但我的代码却没有。这里有什么不对吗?

回答

0

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