Winpcap 开发教程

来源:互联网 发布:社会学属于法学吗 知乎 编辑:程序博客网 时间:2024/05/20 18:03

一、Winpcap开发包能干嘛?

  1. 获取可用网卡的列表

  2. 获取网卡的信息,包括数量,名字,地址

  3. 嗅探抓包
  4. 向网络发数据包
  5. 将从网卡获取的网络流保存到磁盘
  6. 对已经抓取的包进行使用高级语言进行过滤
  7. 跨平台,在windows下用wInpcap开发的网络工具可以在Unix重新编译使用。

二、Winpcap使用到的结构体

三、使用方法

3.1 创建pcap_t对象
函数有:

  • pcap_t * pcap_open_live (const char *device, int snaplen, int promisc, int to_ms, char *ebuf)

Open a live capture from the network. 生成一个实时抓包的pcap_t
- pcap_t * pcap_open_offline (const char *fname, char *errbuf)

Open a savefile in the tcpdump/libpcap format to read packets.
从已经保存的数据包文件,*.pcap结尾的文件创建一个pcap_t

3.2编写回调函数
回调函数原型:

  • typedef void(* pcap_handler )(u_char *user, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)

user:一般为NULL,给用户自定义预留的一个参数
pkt_header:数据包的头结构,里面指示了这个数据包的大小、时间戳
pkt_data:数据包的真实内存区域(从链路层开始的整个数据包)
然后在回调函数已经定义对每一个数据包的操作。

3.3 注册回调函数

  • int pcap_dispatch (pcap_t *p, int cnt, pcap_handler callback, u_char *user)
    Collect a group of packets.
  • int pcap_loop (pcap_t *p, int cnt, pcap_handler callback, u_char *user)
    Collect a group of packets.

其中有了上面这几个函数就可以进行抓包了
3.4
- u_char * pcap_next (pcap_t *p, struct pcap_pkthdr *h)
Return the next available packet.
- int pcap_next_ex (pcap_t *p, struct pcap_pkthdr **pkt_header, const u_char **pkt_data)
Read a packet from an interface or from an offline capture.
- void pcap_breakloop (pcap_t *)
set a flag that will force pcap_dispatch() or pcap_loop() to return rather than looping.
中断抓包

3.5 包过滤

  • int pcap_compile (pcap_t *p, struct bpf_program *fp, char *str, int optimize, bpf_u_int32 netmask)
    Compile a packet filter, converting an high level filtering expression (see Filtering expression syntax) in a program that can be interpreted by the kernel-level filtering engine.

  • int pcap_setfilter (pcap_t *p, struct bpf_program *fp)
    Associate a filter to a capture.

四、一般步骤

  1. 创建pcap_t对象
  2. 编写回调函数
  3. 生成过滤模块
  4. 注册回调函数
原创粉丝点击