`

使用WinPcap编程

 
阅读更多

创建一个使用 wpcap.dll 的应用程序

用 Microsoft Visual C++ 创建一个使用 wpcap.dll 的应用程序,需要按一下步骤:

  • 在每一个使用了库的源程序中,将 pcap.h 头文件包含(include)进来。
  • 如果你在程序中使用了WinPcap中提供给Win32平台的特有的函数, 记得在预处理中加入WPCAP 的定义。
  • 如果你的程序使用了WinPcap的远程捕获功能,那么在预处理定义中加入HAVE_REMOTE不要直接把remote-ext.h直接加入到你的源文件中去。
  • 设置VC++的链接器(Linker),把wpcap.lib库文件包含进来。wpcap.lib可以在WinPcap中找到。
  • 设置VC++的链接器(Linker),把ws2_32.lib库文件包含进来。这个文件分布于C的编译器,并且包含了Windows的一些socket函数。本教程中的一些范例程序,会需要它。

记住以下几点

  • 要添加一个预处理定义,你需要打开Project菜单,选择Settings,然后选择C/C++选项卡,在General类下,你必须在Preprocessor Definitions下的文本框中添加定义。
  • 要在一个VC++6.0工程中,添加一个新的库,你必须打开Project菜单,选择Settings,然后选择Link选项卡,然后把新库的名字添加到Object/Library modules下的文本框中
  • 要向VC++6.0中添加一个新的库所在的路径,你必须打开Tool菜单,选择Options,然后选择Directories选项卡,在Show directories下拉框中选择Library files,并且将新的路径添加到Directories中去
  • 要向VC++6.0中添加一个新的包含文件所在的路径,你必须打开Tool菜单,选择Options,然后选择Directories选项卡,在Show directories下拉框中选择Include files,并且将新的路径添加到Directories中去

 


范例程序

我们一共了一些范例程序来显示WinPcap API的用法。这些程序的源代码,以及编译运行这些代码所需的所有文件,都可以在 Developer's Pack找到。作为教程,在这里,我们提供了浏览器式的代码:这样,在每个函数和变量之间的跳转会比较方便。更多完整的范例程序,请参阅 WinPcap 教程.

Packet Dump

这个程序会依据命令行参数,从网络适配器,或是从文件来读取数据包。如果没有提供源,那么程序会显示出所有可用的适配器,你可以选其中一个。当捕获过程开始,程序会打印数据包的时间戳,长度,原始内容。一旦被编译了,那么它将能运行于所有的Win32平台,当然,它也可以被编译成Unix平台的程序。

 

/*
 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
 * Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the Politecnico di Torino, CACE Technologies 
 * nor the names of its contributors may be used to endorse or promote 
 * products derived from this software without specific prior written 
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */


#include <stdlib.h>
#include <stdio.h>

//
// NOTE: remember to include WPCAP and HAVE_REMOTE among your
// preprocessor definitions.
//

#include <pcap.h>

#define LINE_LEN 16

main(int argc, char **argv)
{   
pcap_if_t *alldevs, *d;
pcap_t *fp;
u_int inum, i=0;
char errbuf[PCAP_ERRBUF_SIZE];
int res;
struct pcap_pkthdr *header;
const u_char *pkt_data;

    printf("pktdump_ex: prints the packets of the network using WinPcap.\n");
    printf("   Usage: pktdump_ex [-s source]\n\n"
           "   Examples:\n"
           "      pktdump_ex -s file://c:/temp/file.acp\n"
           "      pktdump_ex -s rpcap://\\Device\\NPF_{C8736017-F3C3-4373-94AC-9A34B7DAD998}\n\n");

    if(argc < 3)
    {

        printf("\nNo adapter selected: printing the device list:\n");
        /* The user didn't provide a packet source: Retrieve the local device list */
        if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
        {
            fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
            return -1;
        }
        
        /* Print the list */
        for(d=alldevs; d; d=d->next)
        {
            printf("%d. %s\n    ", ++i, d->name);

            if (d->description)
                printf(" (%s)\n", d->description);
            else
                printf(" (No description available)\n");
        }
        
        if (i==0)
        {
            fprintf(stderr,"No interfaces found! Exiting.\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");

            /* Free the device list */
            pcap_freealldevs(alldevs);
            return -1;
        }
        
        /* Jump to the selected adapter */
        for (d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
        
        /* Open the device */
        if ( (fp= pcap_open(d->name,
                            100 /*snaplen*/,
                            PCAP_OPENFLAG_PROMISCUOUS /*flags*/,
                            20 /*read timeout*/,
                            NULL /* remote authentication */,
                            errbuf)
                            ) == NULL)
        {
            fprintf(stderr,"\nError opening adapter\n");
            return -1;
        }
    }
    else 
    {
        // Do not check for the switch type ('-s')
        if ( (fp= pcap_open(argv[2],
                            100 /*snaplen*/,
                            PCAP_OPENFLAG_PROMISCUOUS /*flags*/,
                            20 /*read timeout*/,
                            NULL /* remote authentication */,
                            errbuf)
                            ) == NULL)
        {
            fprintf(stderr,"\nError opening source: %s\n", errbuf);
            return -1;
        }
    }

    /* Read the packets */
    while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
    {

        if(res == 0)
            /* Timeout elapsed */
            continue;

        /* print pkt timestamp and pkt len */
        printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);          
        
        /* Print the packet */
        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)
    {
        fprintf(stderr, "Error reading the packets: %s\n", pcap_geterr(fp));
        return -1;
    }

    return 0;
}


数据包过滤器

这是一个更加完整的使用libpcap的范例程序,它显示了如何创建和设置过滤器,如何把捕获保存到磁盘。这个程序在Win32和Unix平台下都能编译。Pcap_filter(pf.exe)是一个通用的数据包过滤程序:它的输入参数有数据包的源(可以是物理接口,或是一个文件),过滤器和一个输出文件。它会从源获取数据包,并对它们进行过滤,如果它们符合过滤器的要求,就把它们保存到输出文件,直到按下Ctrl+C,或者整个文件处理完毕。Pcap_filter不但可以根据一个特定的过滤器,来堆处理网络中的数据,而且可以从已经保存过的文件中提取数据包。输入和输出文件的格式都是libpcap兼容的格式,比如,WinDump,tcpdump和其他许多网络工具。

 

 

/*
 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
 * Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the Politecnico di Torino, CACE Technologies 
 * nor the names of its contributors may be used to endorse or promote 
 * products derived from this software without specific prior written 
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */


#include <stdlib.h>
#include <stdio.h>

#include <pcap.h>

#define MAX_PRINT 80
#define MAX_LINE 16


void usage();


void main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
char *source=NULL;
char *ofilename=NULL;
char *filter=NULL;
int i;
pcap_dumper_t *dumpfile;
struct bpf_program fcode;
bpf_u_int32 NetMask;
int res;
struct pcap_pkthdr *header;
const u_char *pkt_data;

    if (argc == 1)
    {
        usage();
        return;
    }

    for(i=1;i < argc; i+= 2)
    {

        switch (argv[i] [1])
        {
            case 's':
            {
                source=argv[i+1];
            };
            break;

            case 'o':
            {
                ofilename=argv[i+1];
            };
            break;

            case 'f':
            {
                filter=argv[i+1];
            };
            break;
        }
    }

    // open a capture from the network
    if (source != NULL)
    {
        if ( (fp= pcap_open(source,
                            1514 /*snaplen*/,
                            PCAP_OPENFLAG_PROMISCUOUS /*flags*/,
                            20 /*read timeout*/,
                            NULL /* remote authentication */,
                            errbuf)
                            ) == NULL)
        {
            fprintf(stderr,"\nUnable to open the adapter.\n");
            return;
        }
    }

    else usage();

    if (filter != NULL)
    {
        // We should loop through the adapters returned by the pcap_findalldevs_ex()
        // in order to locate the correct one.
        //
        // Let's do things simpler: we suppose to be in a C class network ;-)
        NetMask=0xffffff;

        //compile the filter
        if(pcap_compile(fp, &fcode, filter, 1, NetMask) < 0)
        {
            fprintf(stderr,"\nError compiling filter: wrong syntax.\n");
            return;
        }

        //set the filter
        if(pcap_setfilter(fp, &fcode)<0)
        {
            fprintf(stderr,"\nError setting the filter\n");
            return;
        }

    }

    //open the dump file
    if (ofilename != NULL)
    {
        dumpfile= pcap_dump_open(fp, ofilename);

        if (dumpfile == NULL)
        {
            fprintf(stderr,"\nError opening output file\n");
            return;
        }
    }
    else usage();

    //start the capture
    while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
    {

        if(res == 0)
        /* Timeout elapsed */
        continue;

        //save the packet on the dump file
        pcap_dump((unsigned char *) dumpfile, header, pkt_data);

    }
}


void usage()
{

    printf("\npf - Generic Packet Filter.\n");
    printf("\nUsage:\npf -s source -o output_file_name [-f filter_string]\n\n");
    exit(0);
}


原文地址:http://www.ferrisxu.com/WinPcap/html/index.html

 

分享到:
评论

相关推荐

    winpcap编程

    WinPcap编程是一种在Windows操作系统下进行网络数据包捕获和分析的技术,它是一个开源库,主要用于网络监控、性能分析、安全检测等多个领域。WinPcap提供了底层的网络访问能力,使得开发者可以直接与网络接口卡(NIC...

    WinPcap+中文技术文档

    使用WinPcap编程 WinPcap教程: 循序渐进教您使用WinPcap 获取设备列表 获取已安装设备的高级信息 打开适配器并捕获数据包 不用回调方法捕获数据包 过滤数据包 分析数据包 处理脱机堆文件 发送数据包 收集并统计网络...

    Winpcap编程 导入文件 wpdpack

    本文将深入探讨Winpcap编程和WpdPack的使用,以及它们在IT领域中的关键应用。 首先,我们需要了解Winpcap的基本概念。Winpcap是一个系统级的库,它提供了在不改变操作系统网络堆栈的情况下,捕获、过滤、修改和发送...

    循序渐进学习WinPcap编程

    总结来说,循序渐进学习WinPcap编程不仅需要熟悉C语言编程和网络基础知识,还需要掌握WinPcap提供的API和函数库,以及其在Visual C++环境中的配置和使用方法。通过逐步学习和实践,开发者可以开发出能够进行复杂网络...

    基于winpcap网络协议编程

    总结,WinPcap为网络协议编程提供了强大的底层支持,通过深入理解和熟练使用它的API,我们可以创建出高效、定制化的网络应用。无论是数据包捕获、过滤,还是发送,都极大地扩展了网络编程的可能性。结合Socket编程,...

    winpcap编程指南

    WinPcap编程指南主要涉及的是在Windows操作系统中利用WinPcap库进行数据包捕获和网络分析的技术。WinPcap是Windows平台上的一个开源库,它提供了底层的网络访问能力,使得开发者能够直接与网络接口卡(NIC)交互,...

    winpcap网络编程资料

    3. **WinPCAP编程接口**: - `pcap_open_live()`: 打开一个网络接口进行实时捕获。 - `pcap_compile()`: 编译过滤表达式,生成过滤器结构体。 - `pcap_setfilter()`: 设置捕获数据包的过滤规则。 - `pcap_loop()...

    winpcap编程捕获数据包

    WinPcap编程捕获数据包是网络编程领域中的一个重要概念,尤其对于网络监控、数据分析以及安全检测等应用来说,它是核心工具之一。WinPcap是一个开源库,它为Windows操作系统提供了底层网络访问能力,允许程序直接与...

    winpcap编程课件

    winpcap编程 winpcap编程 winpcap编程

    基于Winpcap编程实现抓包实验.doc

    基于Winpcap编程实现抓包实验 本文主要介绍基于Winpcap编程实现抓包实验的设计目标、实现步骤、系统流程图和所需函数等。Winpcap是Windows平台上的一种网络嗅探器,通过编程可以实现对网络数据的捕获和分析。 一、...

    WinPcap编程包

    WinPcap编程包是Windows平台下用于网络数据包捕获和网络分析的重要工具。它是一个开源库,提供了底层网络访问的能力,使得开发者可以构建高级的网络监控和安全应用。WinPcap不仅允许程序读取网络接口上的原始数据包...

    3 winpcap编程1

    通过以上介绍,我们可以看到Winpcap编程涉及到网络编程的基础知识,如网络接口的使用、数据包的捕获和解析、以及数据包过滤和发送。这些技能对于网络监控、网络安全分析以及网络应用的开发至关重要。在实际应用中,...

    Winpcap_编程.ppt

    Winpcap编程文档 Winpcap编程文档

    深度剖析WinPcap(网络编程进阶必备)

    对于深入学习网络编程技术的开发者而言,掌握WinPcap的使用技巧是不可或缺的一步。本文将从WinPcap的基本概念出发,逐步深入到其内部实现机制,特别聚焦于获取与释放网络适配器设备列表这一核心功能。 #### 二、...

    自己写的winpcap编程的课件

    自己写的winpcap编程的课件,特别适合初学者,教大三学生时候用的,对象是只有一点c++基础的学生,反映还不错。主要代码课件都有。按照课件可以快速的进行网络编程

    WinPcap_中文技术文档.doc

    4. **使用WinPcap编程**:提供了一系列教程和示例,指导开发者逐步学习如何使用WinPcap进行数据包捕获、分析和发送。 - **获取设备列表**:展示如何获取本地系统中可用的网络设备列表。 - **获取已安装设备的高级...

    WinPcap编程知识

    WinPcap编程知识主要涉及的是在Windows环境下对网络数据包进行捕获和分析的编程技术。WinPcap是一个开源的库,它提供了低级别的网络访问功能,允许开发者直接与网络接口进行交互,进行数据包的捕获、过滤、发送等...

    一个简单的协议分析器

    这些协议是互联网通信的基础,理解它们的工作原理对于网络编程和网络故障排查至关重要。 【TCP(传输控制协议)】:TCP是一种面向连接的、可靠的、基于字节流的传输层通信协议。它通过三次握手建立连接,确保数据...

    循序渐进学习使用WINPCAP

    在使用WINPCAP进行网络编程时,首先需要获取本地的网络适配器列表。这可以通过调用`pcap_findalldevs()`函数实现。这个函数返回一个`pcap_if_t`结构体的链表,其中包含了每个网络设备的信息,如名称、描述以及驱动器...

    winpcap编程中遇到的问题及解决方法

    在进行WinPcap编程时,正确理解并使用数据类型至关重要。这里提到的一些基本类型包括`u_int`、`int`、`u_char`、`char`、`uint8_t`等。 - **`u_int`与`int`**:`u_int`是无符号整型,意味着它只能存储非负数值。而`...

Global site tag (gtag.js) - Google Analytics