1. 抓包 pcap_next
/* libpcap使用案例
* main.cpp
* Created on: Jun 5,2021
* Author :lei
*/
#include <pcap.h>
#include <string.h>
#include <iostream>
#define PCAP_ERRBUF_SIZE 256
using namespace std;
int test01(){
char *dev, errbuf[PCAP_ERRBUF_SIZE];
pcap_t *handle;
/* 获取第一个可用的网口: */
dev = pcap_lookupdev(errbuf);
if(dev ==NULL){
fprintf(stderr,"Couldn't find default device: %sn",errbuf);
return(2);
}
printf("Device:%s\n",dev);
/* 打开监听的设备 */
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if(handle ==NULL){
fprintf(stderr,"Couldn't find default device: %sn",errbuf);
return(2);
}
/* 设置过滤条件 */
bpf_u_int32 net;
bpf_u_int32 mask;
if(pcap_lookupnet(dev, &net, &mask, errbuf)==-1){
fprintf(stderr,"Can't get netmask for device %sn",errbuf);
net = 0;
mask = 0;
return(2);
}
/* 编译过滤条件 */
struct bpf_program fp;
char filter_exp[] = "ip";
if( pcap_compile(handle, &fp, filter_exp , 0, net)==-1){
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
return(2);
}
/* 设置过滤条件 */
if (pcap_setfilter(handle, &fp)==-1){
fprintf(stderr, "Couldn't install filter %s: %sn", filter_exp, pcap_geterr(handle));
return(2);
}
/* 捕捉包 */
const u_char *packet;
pcap_pkthdr header;
if((packet = pcap_next(handle, &header))==NULL){
printf("抓包出错\n");
return 2;
}
printf("jacked a packet with length of [%d]\n", header.len);
printf("packet:%s\n",packet);
/* 输出数据包 */
if (header.len != header.caplen){
printf("Warning! Capture size different than packet size: %d bytes\n", header.len);
}
for (u_int i=0; (i < header.caplen ) ; i++)
{
// Start printing on the next after every 16 octets
if ( (i % 16) == 0) printf("\n");
// Print each octet as hex (x), make sure there is always two characters (.2).
printf("%.2x ", packet[i]);
}
printf("\n");
/*关闭 session */
pcap_close(handle);
return 0;
}