【问题标题】:PCAP Destination and Source are the samePCAP 目标和源相同
【发布时间】:2013-09-06 16:42:09
【问题描述】:

我在使用 libpcap 时遇到了一些问题。我在这个回调中使用pcap_loop()

void pcap_callback(u_char *useless, const struct pcap_pkthdr *pcap_header, const u_char *packet) {  
    struct ether_header *head = (struct ether_header *)packet;
    struct ip *ip = (struct ip *)(packet + sizeof(struct ether_header));

    u_short eth_type = ntohs(head->ether_type);
    const char *s_ipad = inet_ntoa(ip->ip_src);
    const char *d_ipad = inet_ntoa(ip->ip_dst);
    const char *s_host = ether_ntoa((struct ether_addr *)head->ether_shost);
    const char *d_host = ether_ntoa((struct ether_addr *)head->ether_dhost);

    if (eth_type == ETHERTYPE_IP || eth_type == ETHERTYPE_IPV6) {
        NSLog(@"\nPACKET\ns IP  : %s\ns MAC: %s\n\nd IP  : %s\nd MAC: %s\n\n", s_ipad, s_host, d_ipad, d_host);
    }
}

在控制台上,我得到目的地和来源完全相同的数据包。所以IP和MAC地址没有区别。使用过滤器我可以发现数据包都有目的地地址。

这是我用来启动 pcap 的代码:

void sniff() {
    pcap_t *handle;
    char *device;
    char errbuf[PCAP_ERRBUF_SIZE];

    char *net;
    char *mask;
    bpf_u_int32 netp;
    bpf_u_int32 maskp;
    struct in_addr addr;

    device = "en1";

    pcap_lookupnet(device, &netp, &maskp, errbuff);

    addr.s_addr = netp;
    net = inet_ntoa(addr);
    NSLog(@"ROUTER: %s", net);

    addr.s_addr = maskp;
    mask = inet_ntoa(addr);
    NSLog(@"SNMASK: %s", mask);

    handle = pcap_open_live(device, BUFSIZ, 0, 10, errbuf);

    struct bpf_program filterProgram;
    pcap_compile(handle, &filterProgram, "src 10.0.10.40 or dst 10.0.10.40", 1, maskp);
    pcap_setfilter(handle, &filterProgram);

    pcap_loop(handle, 100, pcap_callback, NULL);
    pcap_close(handle);
}

【问题讨论】:

    标签: c++ pcap libpcap


    【解决方案1】:

    来自“man inet_ntoa”: inet_ntoa() 函数将以网络字节顺序给出的 Internet 主机地址转换为 IPv4 点分十进制表示法的字符串。 字符串在静态分配的缓冲区中返回,后续调用将覆盖该缓冲区。

    所以你必须在再次调用inet_ntoa 和ether_ntoa 之前复制s_ipad 和s_host。像这样的:

    const char *aux = inet_ntoa(ip->ip_src);
    const char *s_ipad = strcpy(new char[strlen(aux)+1], aux);
    aux = inet_ntoa(ip->ip_dst);
    const char *d_ipad = strcpy(new char[strlen(aux)+1], aux);
    aux = ether_ntoa((struct ether_addr *)head->ether_shost);
    const char *s_host = strcpy(new char[strlen(aux)+1], aux);
    aux = ether_ntoa((struct ether_addr *)head->ether_dhost);
    const char *d_host = strcpy(new char[strlen(aux)+1], aux);
    //do whatever...    
    delete[] s_ipad; delete[] d_ipad;delete[] s_host; delete[] d_host;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多