Winpcap(二)

                                                     用Winpcap 得到网络驱动列表程序

The first thing that usually a WinPcap based application needs is a list of suitable network adapters. Libpcap provides the pcap_findalldevs() function for this purpose: this function returns a linked list of pcap_if structures, each of which contains comprehensive information about an adapter. In particular the fields name and description contain the name and a human readable description of the device.
The following code retrieves the adapter list and shows it on the screen, printing an error if no adapters are found.
用PCAP写应用程序的第一件事往往就是要获得本地的网卡列表。PCAP提供了pcap_findalldevs()这个函数来实现此功能,这个API返回一个pcap_if结构的连表,连表的每项内容都含有全面的网卡信息:尤其是字段名字和含有名字的描述以及有关驱动器的易读信息。

#include "pcap.h"

main()
{
  pcap_if_t *alldevs;
  pcap_if_t *d;
  int i=0;
  char errbuf[PCAP_ERRBUF_SIZE];
 
  /* 这个API用来获得网卡 的列表 */
  if (pcap_findalldevs(&alldevs, errbuf) == -1)
  {
    fprintf(stderr,"Error in pcap_findalldevs: %s/n", errbuf);
    exit(1);
  }
 
  /* 显示列表的响应字段的内容 */
  for(d=alldevs;d;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;
  }

  /* We don't need any more the device list. Free it */
  pcap_freealldevs(alldevs);
}

有关这段程序的一些说明:
首先pcap_findalldevs()同其他的libpca函数一样有一个errbuf参数,当有异常情况发生时,这个参数会被PCAP填充为某个特定的错误字串。再次,UNIX也同样提供pcap_findalldevs()这个函数,但是请注意并非所有的系统都支持libpcap提供的网络程序接口。所以我门要想写出合适的程序就必须考虑到这些情况(系统不能够返回一些字段的描述信息),在这种情况下我门应该给出类似"No description available"这样的提示。最后结束时别忘了用pcap_freealldevs()释放掉内存资源。

pcap_if结构体如下:
struct pcap_if
{
         struct pcap_if  *next;                  /*多个网卡时使用来显示各个网卡的信息*/
         char  *name;                                /* name to hand to "pcap_open_live()" */
         char  *description;                      /* textual description of interface, or NULL 就是网卡的型号、名字等*/
         struct pcap_addr  *addresses;
         bpf_u_int32   flags;                   /* PCAP_IF_ interface flags */
};
struct pcap_addr
{
        struct pcap_addr  *next;
        struct sockaddr  *addr;                  /* address */
        struct sockaddr  *netmask;           /* netmask for that address */
        struct sockaddr  *broadaddr;         /* broadcast address for that address */
        struct sockaddr  *dstaddr;              /* P2P destination address for that address */
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值