利用libpcap打印ip包

时间:2021-05-05 09:32:18
 #include <stdio.h>
#include <pcap.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <iostream> using namespace std; //IP层数据包格式
typedef struct
{
int header_len:;
int version:;
u_char tos:;
int total_len:;
int ident:;
int flags:;
u_char ttl:;
u_char proto:;
int checksum:;
u_char sourceIP[];
u_char destIP[];
}IPHEADER; void callback(u_char* user,const struct pcap_pkthdr* header,const u_char* pkt_data); int main(int argc, char **argv)
{
char *device = NULL;
char errbuf[];
pcap_t *pcap;
int link_data; if((device = pcap_lookupdev(errbuf)) == NULL)
{
perror(errbuf);
return ;
} pcap = pcap_open_live(device, , , , errbuf);
if(pcap == NULL)
{
perror(errbuf);
return ;
} if((link_data = pcap_datalink(pcap)) == -)
{
fprintf(stderr,"pcap_link_data: %s\n",pcap_geterr(pcap));
return ;
} cout<<"开始抓包"<<endl;
pcap_loop(pcap, -, callback, NULL); return ;
} void callback(u_char* user,const struct pcap_pkthdr* header,const u_char* pkt_data)
{
cout<<"\t\t抓到一个包"<<endl;
cout<<"-------------------------------------------------"<<endl;
//解析数据包IP头部
if(header->len>=){
IPHEADER *ip_header=(IPHEADER*)(pkt_data+);
//解析协议类型
cout<<"|版本 "<<ip_header->version<<"|首部长度"<<ip_header->header_len*<<"字节|\t\t|"
"总长度"<<ip_header->total_len<<"字节|"<<endl;
cout<<"-------------------------------------------------"<<endl;
cout<<"|\t\t\t|\t|\t\t|"<<endl;
cout<<"-------------------------------------------------"<<endl;
cout<<"|ttl "<<int(ip_header->ttl)<<"\t|协议 ";
switch(ip_header->proto)
{
case :
cout<<"ICMP";
break;
case :
cout<<"IGMP";
break;
case :
cout<<"TCP ";
break;
case :
cout<<"UDP ";
break;
case :
cout<<"IPv6";
break;
default:
cout<<"IPv4";
}
cout<<"\t|首部校验和 "<<ip_header->checksum<<"\t|"<<endl;
cout<<"-------------------------------------------------"<<endl;
printf("|\t\t源地址 : %d.%d.%d.%d\t\t|\n",\
ip_header->sourceIP[],ip_header->sourceIP[],ip_header->sourceIP[],ip_header->sourceIP[]);
cout<<"-------------------------------------------------"<<endl;
printf("|\t\t目的地址 : %d.%d.%d.%d\t\t|\n",\
ip_header->destIP[],ip_header->destIP[],ip_header->destIP[],ip_header->destIP[]);
cout<<"-------------------------------------------------"<<endl;
cout<<endl;
}
}

利用libpcap打印ip包