【问题标题】:libpcap source and destination address are always NULL in captured ipheader.libpcap 源地址和目标地址在捕获的 ipheader 中始终为 NULL。
【发布时间】:2011-07-29 14:03:18
【问题描述】:

我编写了一个小程序来玩弄 libpcap。 问题是我捕获的标头的源地址和目标地址字段似乎总是为空。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/if_ether.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <pcap.h>
#include <arpa/inet.h>

#define BUFFERSIZE 65535

char errbuf[PCAP_ERRBUF_SIZE];

void sniffloop(u_char *, const struct pcap_pkthdr *, const u_char *);

void usage(char *name){
    fprintf(stderr, "usage: %s <interface> <secret>", name);
    exit(1);
}

int main(int argc, char **argv){
    pcap_t *sniffsess;
    struct bpf_program filter;

    if(argc<3){
        usage(argv[0]);
        return 1;
    }

    if(!(sniffsess=pcap_open_live(argv[1], BUFFERSIZE, 0, 1000, errbuf))){
        fprintf(stderr, "%s: couldn't open devices for sniffing: %s\n", argv[0], errbuf);
        return 1;
    }

    if(pcap_datalink(sniffsess)!=DLT_EN10MB){
        fprintf(stderr, "%s: %s not an ethernet device", argv[0], argv[1]);
        return 1;
    }

    if(pcap_compile(sniffsess, &filter, "icmp", 0, 0)==-1){
        fprintf(stderr, "%s: couldn't parse icmp filter", argv[0]);
        return 1;
    }

    if(pcap_setfilter(sniffsess, &filter)==-1){
        fprintf(stderr, "%s: couldn't set icmp filter", argv[0]);
        return 1;
    }

    // daemonize here.
    pcap_loop(sniffsess, -1, sniffloop, NULL);
}

void sniffloop(u_char *args, const struct pcap_pkthdr *hdr, const u_char *pkt){
    struct ethhdr *ehdr=(struct ethhdr *)pkt;
    struct iphdr *ipheader=(struct iphdr *)pkt+sizeof(struct ethhdr);
    struct icmphdr *icmpheader=(struct icmphdr*)pkt+sizeof(structethhdr)+ipheader->ihl*4;
    char *data=(char *)pkt+sizeof(struct ethhdr)+ipheader->ihl*4+sizeof(struct icmphdr);
    struct in_addr source,destination;
    source.s_addr=ipheader->saddr;
    destination.s_addr=ipheader->daddr;

    printf("sourceaddress is %p\ndestinationaddess is %p\n", ipheader->saddr, ipheader->daddr);
}

输出:

spongebob code # ./icmpexec br0 foo
sourceaddress is (nil)
destinationaddess is (nil)
sourceaddress is (nil)
destinationaddess is (nil)

我已经搜索了答案,但没有找到任何东西。 我认为很可能是我在协议头中弄错了一些偏移量。

感谢您查看此内容! :D

【问题讨论】:

    标签: c linux networking libpcap


    【解决方案1】:

    你所有的地址计算都是错误的。例如:

    struct iphdr *ipheader=(struct iphdr *)pkt+sizeof(struct ethhdr);
    

    需要:

    struct iphdr *ipheader=(struct iphdr *)(pkt+sizeof(struct ethhdr));
    

    【讨论】:

    • 嗯,好的,谢谢你的提示。但是这两种说法有什么区别呢?这不是简单地添加地址+偏移量吗?
    • @Hubert 在第一条语句中,您正在向 (struct iphdr*)pkt 添加偏移量。根据 C 的规则,这意味着您有效地获取了 ((struct iphdr*)pkt)[sizeof(struct ethhdr)] 的地址。换句话说,偏移量乘以 sizeof(struct iphdr)。在第二种情况下,您正在向 (char *) 添加偏移量,因此偏移量乘以 sizeof(char),即 1。
    猜你喜欢
    • 2021-06-21
    • 2016-05-16
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    相关资源
    最近更新 更多