winpcap是windows系统网络抓包的一个库,在linux中也对应一个库为libpcap,两者使用是一样的。
1.pcap_lookupdev():查找网卡设备
char *pcap_lookupdev(char *errbuf)
errbuf为出错信息,如果出错errbuf会有内容,返回值为设备名指针(返回NULL说明未发现设备)
2.pcap_lookupnet():获取ip地址:
int pcap_lookupnet(char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp, char *errbuf):
device为指定的设备名,netp会返回设备ip,maskp返回设备掩码,errbuf返回出错信息
3.pcap_open_live():开启对应的网卡设备
pcap_t *pcap_open_live(char *device, int snaplen, int promisc, int to_ms, char *errbuf);
device为设备名,snaplen为指定每次获取一个包的最大的内容,promisc设置是否为混杂模式,to_ms等待毫秒,errbuf出错信息
4.pcap_compile():添加过滤选项
int pcap_compile(pcap_t *p, struct bpf_program *fp, char *buf, int optmize, bpf_u_int32 mask);
fp存放编译后的bpf, buf为过滤条件,optimize是否优化过滤表,mask为网络掩码
5.pcap_setfilter():设置开启过滤器
int pacap_setfilter(pcap_t *p, struct bpf_program *fp);
6.pcap_loop():循环获取网卡数据
int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user);
p是pcap_open_live返回的值, cnt指抓几个包(无限抓包则为-1),callback回调函数(执行数据处理操作),user(回调函数的第一个para)
7.pcap_close():关闭
void pcap_close(pcap_t *p);
p是pcap_open_live返回值
网上的一段程序
- #include
- #include
- #include
- #include
-
- void getPacket(u_char * arg, const struct pcap_pkthdr * pkthdr, const u_char * packet)
- {
- int * id = (int *)arg;
-
- printf("id: %d\n", ++(*id));
- printf("Packet length: %d\n", pkthdr->len);
- printf("Number of bytes: %d\n", pkthdr->caplen);
- printf("Recieved time: %s", ctime((const time_t *)&pkthdr->ts.tv_sec));
-
- int i;
- for(i=0; ilen; ++i)
- {
- printf(" %02x", packet[i]);
- if( (i + 1) % 16 == 0 )
- {
- printf("\n");
- }
- }
-
- printf("\n\n");
- }
-
- int main()
- {
- char errBuf[PCAP_ERRBUF_SIZE], * devStr;
-
- /* get a device */
- devStr = pcap_lookupdev(errBuf);
-
- if(devStr)
- {
- printf("success: device: %s\n", devStr);
- }
- else
- {
- printf("error: %s\n", errBuf);
- exit(1);
- }
-
- /* open a device, wait until a packet arrives */
- pcap_t * device = pcap_open_live(devStr, 65535, 1, 0, errBuf);
-
- if(!device)
- {
- printf("error: pcap_open_live(): %s\n", errBuf);
- exit(1);
- }
-
- /* construct a filter */
- struct bpf_program filter;
- pcap_compile(device, &filter, "dst port 80", 1, 0);
- pcap_setfilter(device, &filter);
-
- /* wait loop forever */
- int id = 0;
- pcap_loop(device, -1, getPacket, (u_char*)&id);
-
- pcap_close(device);
-
- return 0;
- }
参考博客:
http://blog.csdn.net/u011573853/article/details/49963567
https://www.baidu.com/link?url=7GUWfVIPinwVoqC4NRxvUfU1xlCQCs2JW_IVsW4nf5nAM2SH-hytF8c3B7Y6NkYXYyQbn4W743zl5lV1-AAdhq&wd=&eqid=d6d1f9660005ea1b000000065972ede5