2013-03-02 48 views
1

我想写一个简单的应用程序来输出dst和src TCP端口号。为了测试,我尝试应用pcap过滤器来仅侦听端口80或来自端口80的数据包。但是,尽管所有内容对我来说都是正确的,但我始终得到端口号为0的端口号。大约10%的时间我得到了5位数的端口号。任何人都可以给我任何提示,我可能会做错什么?偶尔的TCP头部端口号0

#include<pcap.h> 
#include<stdio.h> 
#include<net/ethernet.h> 
#include<netinet/ip.h> 
#include<netinet/tcp.h> 
#include<arpa/inet.h> 

void handle_packet(u_char* args, const struct pcap_pkthdr* pkthdr, const u_char* p) 
{ 
    struct iphdr* ip_hdr; 
    struct tcphdr* tcp_hdr; 

    ip_hdr = (struct iphdr*) (p+sizeof(struct ether_header)); 
    tcp_hdr = (struct tcphdr*) (ip_hdr+sizeof(struct iphdr)); 
    printf("src:%d\n", ntohs(tcp_hdr->source)); 
    printf("dst:%d\n", ntohs(tcp_hdr->dest)); 
} 

int main(int argc, char** argv) 
{ 
    pcap_t *handle;    /* Session handle */ 
    char *dev;      /* The device to sniff on */ 
    char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */ 
    struct bpf_program filter;  /* The compiled filter */ 
    char filter_app[] = "tcp port 80"; /* The filter expression */ 
    bpf_u_int32 mask;    /* Our netmask */ 
    bpf_u_int32 net;    /* Our IP */ 

    /* Define the device */ 
    dev = pcap_lookupdev(errbuf); 

    /* Find the properties for the device */ 
    pcap_lookupnet(dev, &net, &mask, errbuf); 

    /* Open the session in promiscuous mode */ 
    handle = pcap_open_live(dev, BUFSIZ, 0, 0, errbuf); 

    /* Compile and apply the filter */ 
    pcap_compile(handle, &filter, filter_app, 0, net); 
    pcap_setfilter(handle, &filter); 

    pcap_loop(handle, 10, handle_packet, NULL); 

    pcap_close(handle); 
    return(0); 
} 

回答

3

这里有两个问题。首先,请记住C中的指针算术是,比例为。所以,当你这样说:

tcp_hdr = (struct tcphdr*) (ip_hdr+sizeof(struct iphdr)); 

你实际上推进更为字节比您预期(sizeof(struct iphdr) * sizeof(struct iphdr)是精确的)。为了实现你想要的东西你可以说:

tcp_hdr = (struct tcphdr*) &ip_hdr[1]; 

但是这也行不通。 IP标头没有固定的长度。相反,你应该检查头的ihl场和计算应该看起来更像是这样的:

tcp_hdr = (struct tcphdr*) ((char*)ip_hdr + 4*ip_hdr->ihl); /* ihl is the number of 32-bit words in the header */ 

警告:我不知道关于以太网帧,如果他们的头部有一个固定的长度。您还需要验证。