2

我正在尝试编写一个简单的应用程序来输出 dst 和 src TCP 端口号。为了测试,我尝试应用 pcap 过滤器来仅嗅探进出端口 80 的数据包。但是,尽管一切看起来对我来说都是正确的,但我一直得到端口号 0。大约 10% 的时间我得到一个 5 位数的端口号。谁能给我任何提示我可能做错了什么?

#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);
}
4

1 回答 1

4

这里有两个问题。一方面,请记住 C 中的指针算术是scaled。所以,当你说这样的话:

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 */

警告:我不确定以太网帧以及它们的标头是否具有固定长度。您还需要验证这一点。

于 2013-03-02T20:15:52.593 回答