網絡數據包檢測
數據包捕獲(sniffer):是指在網絡上進行數據收集的行為,需要通過網卡來完成。
三種訪問方式:
BSD Packet Filter(BPF)
SVR4 Datalink Provider Interface(DLPI)
linux SOCK_PACKET interface
libpcap庫
安裝:
apt-get install libpcap-dev
常用API
捕獲數據包
查找缺省的用來捕獲數據網絡設備
char * pcap_lookupdev ( char * errbuf )//出錯時保存系統返回的錯誤信息。
返回值:
成功時返回指向設備名稱的指針,
失敗返回NULL
查找指定設備的網絡號和子網掩碼
int pcap_lookupnet( const char * device,//指向設備名稱的指針
bpf_u_int32 * netp,//指向獲取的網絡號的指針
bpf_u_int32 * maskp,//指向獲取的子網掩碼的指針
char * errbuf)//出錯時保存系統返回的錯誤信息
返回值:
成功返回0,
失敗返回-1,並保存錯誤信息到errbuf中。
打開一個網絡設備用於捕獲數據包
pcap_t * pcap_open_live( const char * device,//指向設備名稱的指針
int snaplen, //捕獲的數據包的長度
int promisc,//網絡接口工作模式
int to_ms,//讀取數據包時的超時
char * errbuf)//出錯時保存系統錯誤信息
返回值:
成功返回捕獲數據包的句柄
失敗返回NULL並保存錯誤信息到errbuf中
捕獲下一幀數據
const u_char * pcap_next ( pcap_t * p//pcap_open_live返回的句柄
struct pcap_pkthdr * h)保存捕獲的數據包屬性的結構體指針
返回值:
成功時返回捕獲的數據幀的指針,
失敗或無數據返回NULL。
循環捕獲多幀數據並處理
typedef void ( * pcap_handler )( u_char *user,
const struct pcap_pkthdr * h,const u_char *bytes);
int pcap_loop( pcap_t * p,//pcap_open_live返回的句柄
int cnt,//要捕獲的數據幀的個數
pcap_handler callback,//捕獲到一幀數據時執行的處理函數
u_char * user )//傳遞給callback的參數
查看本欄目更多精彩內容:http://www.bianceng.cn/OS/unix/
返回值:
成功返回0,
失敗返回-1,
被中斷返回-2.
過濾數據包
根據過濾器表達式生成過濾器
int * pcap_compile( pcap_t * p,//pcap_open_live返回的句柄
struct bpf_program * fp,//保存過濾器的結構體指針
const char * str,//要轉換的過濾器表達式
int optimize,//過濾程序是否優化
bpf_u_int32 netmask )//子網掩碼
返回值:
成功返回0,
失敗返回-1。
為指定的捕捉句柄安裝過濾器
int pcap_next ( pcap_t * p//pcap_open_live返回的句柄
struct bpf_program * fp);//指向要安裝的過濾器的指針
返回值:
成功返回0;
失敗返回-1.
捕獲數據包流程
示例程序:
//ping.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <netdb.h> #include <setjmp.h> #include <errno.h> #define PACKET_SIZE 4096 #define MAX_WAIT_TIME 5 #define MAX_NO_PACKETS 3 char sendpacket[PACKET_SIZE]; char recvpacket[PACKET_SIZE]; int sockfd,datalen=56; int nsend=0,nreceived=0; struct sockaddr_in dest_addr; pid_t pid; struct sockaddr_in from; struct timeval tvrecv; void f(int signo) {} void statistics(int signo); unsigned short cal_chksum(unsigned short *addr,int len); int pack(int pack_no); void send_packet(void); void recv_packet(void); int unpack(char *buf,int len); void tv_sub(struct timeval *out,struct timeval *in); void statistics(int signo) { printf("\n--------------------PING statistics-------------------\n"); printf("%d packets transmitted, %d received , %%%.2f lost\n",nsend,nreceived,(float)(nsend-nreceived)/nsend*100); close(sockfd); exit(1); } /*校驗和算法*/ unsigned short cal_chksum(unsigned short *addr,int len) { int nleft=len; int sum=0; unsigned short *w=addr; unsigned short answer=0; /*把ICMP報頭二進制數據以2字節為單位累加起來*/ while(nleft>1) { sum+=*w++; nleft-=2; } /*若ICMP報頭為奇數個字節,會剩下最後一字節。把最後一個字節視為一個2字節數據的高字節, 這個2字節數據的低字節為0,繼續累加*/ if( nleft==1) { *(unsigned char *)(&answer)=*(unsigned char *)w; sum+=answer; } sum=(sum>>16)+(sum&0xffff); sum+=(sum>>16); answer=~sum; return answer; } /*設置ICMP報頭*/ int pack(int pack_no) { int i,packsize; struct icmp *icmp; struct timeval *tval; icmp=(struct icmp*)sendpacket; //char sendpacket[4096]; icmp->icmp_type=ICMP_ECHO; icmp->icmp_code=0; #if 1 icmp->icmp_seq=pack_no; icmp->icmp_cksum = 0; #endif icmp->icmp_id=pid; packsize=8+datalen; tval= (struct timeval *)icmp->icmp_data; gettimeofday(tval,NULL); /*記錄發送時間*/ icmp->icmp_cksum=cal_chksum( (unsigned short *)icmp,packsize); /*校驗算法*/ return packsize; } /*發送三個ICMP報文*/ void send_packet() { int packetsize; //while(nsend) //{ nsend++; packetsize=pack(nsend); /*設置ICMP報頭*/ if(sendto(sockfd,sendpacket,packetsize,0,(struct sockaddr *)&dest_addr,sizeof(dest_addr))<0 ) { perror("sendto error"); return; } // sleep(1); /*每隔一秒發送一個ICMP報文*/ // } } /*接收所有ICMP報文*/ void recv_packet() { int n,fromlen; extern int errno; struct sigaction act; sigaction(SIGALRM, NULL, &act); act.sa_handler = f; sigaction(SIGALRM, &act, NULL); fromlen=sizeof(from); while(1) { alarm(5); if( (n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),0,(struct sockaddr *)&from,&fromlen)) <0) { if (errno == EINTR) { printf("errno=%d\n", errno); break; } else exit(-1); } gettimeofday(&tvrecv,NULL); /*記錄接收時間*/ if(unpack(recvpacket,n)==-1) { continue; } else { nreceived++; break; } } } /*剝去ICMP報頭*/ int unpack(char *buf,int len) { int i,iphdrlen; struct ip *ip; struct icmp *icmp; struct timeval *tvsend; double rtt; ip=(struct ip *)buf; iphdrlen=ip->ip_hl<<2; /*求ip報頭長度,即ip報頭的長度標志乘4*/ icmp=(struct icmp *)(buf+iphdrlen); /*越過ip報頭,指向ICMP報頭*/ len-=iphdrlen; /*ICMP報頭及ICMP數據報的總長度*/ if(len<8) /*小於ICMP報頭長度則不合理*/ { printf("ICMP packets\'s length is less than 8\n"); return -1; } /*確保所接收的是我所發的的ICMP的回應*/ if( (icmp->icmp_type==ICMP_ECHOREPLY) && (icmp->icmp_id==pid) ) { tvsend=(struct timeval *)icmp->icmp_data; tv_sub(&tvrecv,tvsend); /*接收和發送的時間差*/ rtt=tvrecv.tv_sec*1000+(float)tvrecv.tv_usec/1000; /*以毫秒為單位計算rtt*/ /*顯示相關信息*/ printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%.3f ms\n", len,inet_ntoa(from.sin_addr),icmp->icmp_seq,ip->ip_ttl,rtt); } else return -1; } int main(int argc,char *argv[]) { struct hostent *host; struct protoent *protocol; unsigned long inaddr=0l; int waittime=MAX_WAIT_TIME; int size=50*1024; if(argc<2) { printf("usage:%s hostname/IP address\n",argv[0]); exit(1); } if( (protocol=getprotobyname("icmp") )==NULL) { perror("getprotobyname"); exit(1); } /*生成使用ICMP的原始套接字,這種套接字只有root才能生成*/ if( (sockfd=socket(AF_INET,SOCK_RAW,protocol->p_proto) )<0) { perror("socket error"); exit(1); } /* 回收root權限,設置當前用戶權限*/ setuid(getuid()); /*擴大套接字接收緩沖區到50K這樣做主要為了減小接收緩沖區溢出的 的可能性,若無意中ping一個廣播地址或多播地址,將會引來大量應答*/ setsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,&size,sizeof(size) ); bzero(&dest_addr,sizeof(dest_addr)); dest_addr.sin_family=AF_INET; /*判斷是主機名還是ip地址*/ if( (inaddr=inet_addr(argv[1]))==INADDR_NONE) { if((host=gethostbyname(argv[1]) )==NULL) /*是主機名*/ { perror("gethostbyname error"); exit(1); } memcpy( (char *)&dest_addr.sin_addr,host->h_addr,host->h_length); } else /*是ip地址*/ dest_addr.sin_addr.s_addr = inaddr; //memcpy( (char *)&dest_addr,(char *)&inaddr,host->h_length); /*獲取main的進程id,用於設置ICMP的標志符*/ pid=getpid(); printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[1], inet_ntoa(dest_addr.sin_addr),datalen); int i = 0; bzero(sendpacket, PACKET_SIZE); bzero(recvpacket, PACKET_SIZE); while (i < 3) { send_packet(); /*發送所有ICMP報文*/ recv_packet(); /*接收所有ICMP報文*/ sleep(1); i++; } statistics(SIGALRM); /*進行統計*/ return 0; } /*兩個timeval結構相減*/ void tv_sub(struct timeval *out,struct timeval *in) { if( (out->tv_usec-=in->tv_usec)<0) { --out->tv_sec; out->tv_usec+=1000000; } out->tv_sec-=in->tv_sec; } /*------------- The End -----------*/
查看本欄目更多精彩內容:http://www.bianceng.cn/OS/unix/
//cap.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pcap.h> #define MAXBYTES2CAPTURE 2048 void process_packet(u_char *arg, const struct pcap_pkthdr *pkthdr, const u_char *packet) { int i = 0, *counter = (int *)arg; printf("packet count:%d\n", ++(*counter)); printf("received packet size %d\n", pkthdr->len); printf("payload\n"); for (i = 0; i < pkthdr->len; i++) { printf("%02x ", (unsigned int)packet[i]); if ((i % 16 == 15 && i != 0) || (i == pkthdr->len-1)) printf("\n"); } printf("\n\n**************\n"); return; } int main(int argc, char *argv[]) { int i = 0, count = 0; pcap_t *descr = NULL; char errbuf[PCAP_ERRBUF_SIZE], *device = NULL; bpf_u_int32 netaddr = 0, mask = 0; struct bpf_program filter; memset(errbuf, 0, sizeof(errbuf)); if (argc != 2) device = pcap_lookupdev(errbuf); else device = argv[1]; printf("Try to open device %s\n", device); if ((descr = pcap_open_live(device, MAXBYTES2CAPTURE, 1, 0, errbuf)) == NULL ) { printf("error:%s\n", errbuf); exit(-1); } printf("pcap_open\n"); pcap_lookupnet(device, &netaddr, &mask, errbuf); printf("pcap_look\n"); //if (pcap_compile(descr, &filter, "arp and ether host 00:0c:29:b7:f6:33", 0, mask) < 0) if (pcap_compile(descr, &filter, "arp and ether host 00:0c:29:cd:d6:dd", 0, mask) < 0) { printf("pcap_compile error\n"); exit(-1); } printf("compile\n"); pcap_setfilter(descr, &filter); printf("setfilter\n"); pcap_loop(descr, 1, process_packet, (u_char *)&count); return 0; }
作者:csdn博客 ctthuangcheng