lvxuzhou


私信TA

用户名:lvxuzhou

访问量:97342

签 名:

lvxuzhou

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

  自我简介:

    这里使用pcap_next_ex()代替了pcap_loop()回调方式,pcap_next_ex()函数的作用就是从一个适配器或者文件中读取一个数据包,这里程序通过while循环一直读到EOF为止。

#include "pcap.h"
#include <QCoreApplication>
#include <winsock2.h>
#include <ws2tcpip.h>
#define LINE_LEN 16
void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *);
int main(int argc, char *argv[]) {
  QCoreApplication a(argc, argv);

  pcap_t *fp;
  char errbuf[PCAP_ERRBUF_SIZE];
  char source[PCAP_BUF_SIZE];

  struct pcap_pkthdr *header;
  const u_char *pkt_data;
  u_int i = 0;
  int res;
  /* 检查程序输入参数 */
  if (argc != 2) {
    printf("usage: %s filename", argv[0]);
    return -1;
  }
  /* 根据新WinPcap语法创建一个源字符串 */
  if (pcap_createsrcstr(source,        // 源字符串
                        PCAP_SRC_FILE, // 我们要打开的文件
                        NULL,          // 远程主机
                        NULL,          // 远程主机端口
                        argv[1],       // 我们要打开的文件名
                        errbuf         // 错误缓冲区
                        ) != 0) {
    fprintf(stderr, "\nError creating a source string\n");
    return -1;
  }
  /* 打开设备 */
  if ((fp = pcap_open(
           source, // 设备名
           65535, // 65535保证能捕获到不同数据链路层上的每个数据包的全部内容
           PCAP_OPENFLAG_PROMISCUOUS, // 混杂模式
           1000,                      // 读取超时时间
           NULL,                      // 远程机器验证
           errbuf                     // 错误缓冲池
           )) == NULL) {
    fprintf(stderr,
            "\nUnable to open the adapter. %s is not supported by WinPcap\n",
            source);
    /* 释放设备列表 */

    return -1;
  }

  /* 从文件获取数据包 */
  while ((res = pcap_next_ex(fp, &header, &pkt_data)) >= 0) {
    /* 打印pkt时间戳和pkt长度 */
    printf("%ld:%ld (%u)\n", header->ts.tv_sec, header->ts.tv_usec,
           header->len);

    /* 打印数据包 */
    for (i = 1; (i < header->caplen + 1); i++) {
      printf("%.2x ", pkt_data[i - 1]);
      if ((i % LINE_LEN) == 0)
        printf("\n");
    }

    printf("\n\n");
  }
  if (res == -1) {
    printf("Error reading the packets: %s\n", pcap_geterr(fp));
  }
  return a.exec();
}


 

0.0分

0 人评分

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

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区