lvxuzhou


私信TA

用户名:lvxuzhou

访问量:97339

签 名:

lvxuzhou

等  级
排  名 48
经  验 11191
参赛次数 0
文章发表 56
年  龄 0
在职情况 学生
学  校 西安
专  业

  自我简介:

  前面都是讲解如何获取适配器信息以及捕获数据包,从这一节开始讲一下WinPcap中更强大的一些特性。本节主要讲一下如何利用WinPcap来过滤数据包。在WinPcap中用来过滤数据包的函数有两个,pcap_compile()和pcap_setfilter()。pcap_compile()的原理是将高层的布尔过滤表达式编译成能够被过滤引擎所解释的低层的字节码,关于布尔过滤表达式的语法会在后续的章节里进行说明。pcap_setfilter()的原理是将一个过滤器与内核捕获会话相关联,当pcap_setfilter()被调用时,过滤器会应用到来自网络的所有数据包,符合要求的所有数据包都将会被立刻复制给应用程序。

      以下代码展示了如何编译并设置过滤器。因为使用pcap_compile()创建的过滤器要使用到掩码,我们必须从pcap_if结构体中获得它

一、函数介绍

if (d->addresses != NULL)
        /* 获取接口第一个地址的掩码 */
        netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
    else
        /* 如果这个接口没有地址,那么我们假设这个接口在C类网络中 */
        netmask=0xffffff; 
compile the filter
    if (pcap_compile(adhandle, &fcode, "ip and tcp", 1, netmask) < 0)
    {
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
        /* 释放设备列表 */
        pcap_freealldevs(alldevs);
        return -1;
    }
    
set the filter
    if (pcap_setfilter(adhandle, &fcode) < 0)
    {
        fprintf(stderr,"\nError setting the filter.\n");
        /* 释放设备列表 */
        pcap_freealldevs(alldevs);
        return -1;
    }

    在这段代码中,传递给pcap_compile()的过滤器是“ip and tcp”,即程序最终可以得到IPV4和TCP的数据包,并把它们复制给应用程序。由于前两节有讲到如何捕获数据包,将捕获和过滤数据包的知识结合到一起,给出一个简单实用的程序。该程序的主要目的是展示如何解析所捕获的数据包的协议首部,这里我们选择分析UDP协议。

#include "pcap.h"
#include <QCoreApplication>
#include <winsock2.h>
#include <ws2tcpip.h>
/* 4字节的IP地址 */
typedef struct ip_address {
  u_char byte1;
  u_char byte2;
  u_char byte3;
  u_char byte4;
} ip_address;
/* IPv4 首部 */
typedef struct ip_header {
  u_char ver_ihl;         // 版本 (4 bits) + 首部长度 (4 bits)
  u_char tos;             // 服务类型(Type of service)
  u_short tlen;           // 总长(Total length)
  u_short identification; // 标识(Identification)
  u_short
      flags_fo; // 标志位(Flags) (3 bits) + 段偏移量(Fragment offset) (13 bits)
  u_char ttl;       // 存活时间(Time to live)
  u_char proto;     // 协议(Protocol)
  u_short crc;      // 首部校验和(Header checksum)
  ip_address saddr; // 源地址(Source address)
  ip_address daddr; // 目的地址(Destination address)
  u_int op_pad;     // 选项与填充(Option + Padding)
} ip_header;
/* UDP 首部*/
typedef struct udp_header {
  u_short sport; // 源端口(Source port)
  u_short dport; // 目的端口(Destination port)
  u_short len;   // UDP数据包长度(Datagram length)
  u_short crc;   // 校验和(Checksum)
} udp_header;
/* 回调函数原型 */
void packet_handler(u_char *param, const struct pcap_pkthdr *header,
                    const u_char *pkt_data);
int main(int argc, char *argv[]) {
  QCoreApplication a(argc, argv);

  pcap_if_t *alldevs;
  pcap_if_t *d;
  int i = 0;
  int inum;

  pcap_t *adhandle;

  char errbuf[PCAP_ERRBUF_SIZE];
  u_int netmask;
  char packet_filter[] = "ip and udp";
  struct bpf_program fcode;

  /* 获取本地机器设备列表 */
  if (pcap_findalldevs_ex((char *)PCAP_SRC_IF_STRING,
                          NULL /* auth is not needed */, &alldevs,
                          errbuf) == -1) {
    fprintf(stderr, "Error in pcap_findalldevs_ex: %s\n", errbuf);
    exit(1);
  }

  /* 打印列表 */
  for (d = alldevs; d != NULL; d = d->next) {
    printf("%d. %s", ++i, d->name);
    if (d->description)
      printf(" (%s)\n", d->description);
    else
      printf(" (No description available)\n");
  }
  if (i == 0) {
    printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
    return -1;
  }
  printf("Enter the interface number (1-%d):", i);
  scanf("%d", &inum);
  if (inum < 1 || inum > i) {
    printf("\nInterface number out of range.\n");
    /* 释放设备列表 */
    pcap_freealldevs(alldevs);
    return -1;
  }
  /* 跳转到选中的适配器 */
  for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++)
    ;

  /* 打开设备 */
  if ((adhandle = pcap_open(
           d->name, // 设备名
           65535, // 65535保证能捕获到不同数据链路层上的每个数据包的全部内容
           PCAP_OPENFLAG_PROMISCUOUS, // 混杂模式
           1000,                      // 读取超时时间
           NULL,                      // 远程机器验证
           errbuf                     // 错误缓冲池
           )) == NULL) {
    fprintf(stderr,
            "\nUnable to open the adapter. %s is not supported by WinPcap\n",
            d->name);
    /* 释放设备列表 */
    pcap_freealldevs(alldevs);
    return -1;
  }
  /* 检查数据链路层,为了简单,我们只考虑以太网 */
  if (pcap_datalink(adhandle) != DLT_EN10MB) {
    fprintf(stderr, "\nThis program works only on Ethernet networks.\n");
    /* 释放设备列表 */
    pcap_freealldevs(alldevs);
    return -1;
  }
  if (d->addresses != NULL)
    /* 获得接口第一个地址的掩码 */
    netmask =
        ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
  else
    /* 如果接口没有地址,那么我们假设一个C类的掩码 */
    netmask = 0xffffff;
  //编译过滤器
  if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) < 0) {
    fprintf(stderr,
            "\nUnable to compile the packet filter. Check the syntax.\n");
    /* 释放设备列表 */
    pcap_freealldevs(alldevs);
    return -1;
  }

  //设置过滤器
  if (pcap_setfilter(adhandle, &fcode) < 0) {
    fprintf(stderr, "\nError setting the filter.\n");
    /* 释放设备列表 */
    pcap_freealldevs(alldevs);
    return -1;
  }

  printf("\nlistening on %s...\n", d->description);

  /* 不再需要设备列表了,释放它 */
  pcap_freealldevs(alldevs);
  /* 开始捕捉 */
  pcap_loop(adhandle, 0, packet_handler, NULL);

  return a.exec();
}
/* 回调函数,当收到每一个数据包时会被libpcap所调用 */
void packet_handler(u_char *param, const struct pcap_pkthdr *header,
                    const u_char *pkt_data) {
  struct tm *ltime;
  char timestr[16];
  ip_header *ih;
  udp_header *uh;
  u_int ip_len;
  u_short sport, dport;
  time_t local_tv_sec;

  /* 将时间戳转换成可识别的格式 */
  local_tv_sec = header->ts.tv_sec;
  ltime = localtime(&local_tv_sec);
  strftime(timestr, sizeof timestr, "%H:%M:%S", ltime);

  /* 打印数据包的时间戳和长度 */
  printf("%s.%.6ld len:%d ", timestr, header->ts.tv_usec, header->len);

  /* 获得IP数据包头部的位置 */
  ih = (ip_header *)(pkt_data + 14); //以太网头部长度

  /* 获得UDP首部的位置 */
  ip_len = (ih->ver_ihl & 0xf) * 4;
  uh = (udp_header *)((u_char *)ih + ip_len);

  /* 将网络字节序列转换成主机字节序列 */
  sport = ntohs(uh->sport);
  dport = ntohs(uh->dport);

  /* 打印IP地址和UDP端口 */
  printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n", ih->saddr.byte1, ih->saddr.byte2,
         ih->saddr.byte3, ih->saddr.byte4, sport, ih->daddr.byte1,
         ih->daddr.byte2, ih->daddr.byte3, ih->daddr.byte4, dport);
}

    我们将过滤器设置为“ip and udp”,这种情况下packet_handler()只会收到基于IPV4的UDP数据包。实例程序还分别创建了用于描述IP首部和UDP首部的结构体,这些结构体中的各种数据会被packet_handler()合理地定位。因为我们需要解析IP数据包,从IP数据包的首部解析到源IP地址和目的IP地址,而IP数据包的首部位于MAC首部的后面,所以我们需要跳过MAC首部。对于以太网而言MAC首部长度为14位, 所以我们在捕捉之前,使用了pcap_datalink()对MAC层进行了检测,以确保我们是处于一个以太网中。处理UDP的首部有一点复杂,因为IP数据包的长度不固定。然而,我们可以通过IP数据包的length域来得到它的长度。一旦解析到了UDP首部的位置,我们就可以解析到源端口和目的端口。程序运行结果截图如下:

QQ图片20211026231104.png

 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区