|
|
在第一章中演示了如何获得已存在适配器的静态信息 在第一章中演示了如何获得已存在适配器的静态信息。实际上WinPcap同样也提供其他的高级信息,特别是 pcap_findalldevs()这个函数返回的每个 pcap_if结构体都同样包含一个pcap_addr结构的列表,他包含: 一个地址列表,一个掩码列表,一个广播地址列表和一个目的地址列表。 下面的例子通过一个ifprint()函数打印出了pcap_if结构的的所有字段信息,该程序对每一个pcap_findalldevs()所返回的pcap_if结构循环调用ifprint()来显示详细的字段信息。
#include "pcap.h" #ifndef WIN32 #include #include #else #include #endif
void ifprint(pcap_if_t *d); char *iptos(u_long in);
int main() { pcap_if_t *alldevs; pcap_if_t *d; char errbuf[PCAP_ERRBUF_SIZE+1];
/* 获得网卡的列表 */ if (pcap_findalldevs(&alldevs, errbuf) == -1) { fprintf(stderr,"Error in pcap_findalldevs: %s\n",errbuf); exit(1); }
/* 循环调用ifprint() 来显示pcap_if结构的信息*/ for(d=alldevs;d;d=d->next) { ifprint(d); }
return 1; }
/* Print all the available information on the given interface */ void ifprint(pcap_if_t *d) { pcap_addr_t *a;
/* Name */ printf("%s\n",d->name);
/* Description */ if (d->description) printf("\tDescription: %s\n",d->description);
/* Loopback Address*/ printf("\tLoopback: %s\n",(d->flags & PCAP_IF_LOOPBACK)?"yes":"no");
/* IP addresses */ for(a=d->addresses;a;a=a->next) { printf("\tAddress Family: #%d\n",a->addr->sa_family);
/*关于 sockaddr_in 结构请参考其他的网络编程书*/ switch(a->addr->sa_family) { case AF_INET: printf("\tAddress Family Name: AF_INET\n");//打印网络地址类型 if (a->addr)//打印IP地址 printf("\tAddress: %s\n",iptos(((struct sockaddr_in *)a->addr)->sin_addr.s_addr)); if (a->netmask)//打印掩码 printf("\tNetmask: %s\n",iptos(((struct sockaddr_in *)a->netmask)->sin_addr.s_addr)); if (a->broadaddr)//打印广播地址 printf("\tBroadcast Address: %s\n",iptos(((struct sockaddr_in *)a->broadaddr)->sin_addr.s_addr)); if (a->dstaddr)//目的地址 printf("\tDestination Address: %s\n",iptos(((struct sockaddr_in *)a->dstaddr)->sin_addr.s_addr)); break; default: printf("\tAddress Family Name: Unknown\n"); break; } } printf("\n"); }
/* 将一个unsigned long 型的IP转换为字符串类型的IP */ #define IPTOSBUFFERS 12 char *iptos(u_long in) { static char output[IPTOSBUFFERS][3*4+3+1]; static short which; u_char *p;
p = (u_char *)∈ which = (which + 1 == IPTOSBUFFERS ? 0 : which + 1); sprintf(output[which], "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); return output[which]; }
|