| 发表于:2007-12-15 15:48:26 楼主 |
#include "pcap.h" //#include <stdlib.h> struct ether_header { u_int8_t ether_dhost[6]; u_int8_t ether_shost[6]; u_int16_t ether_type; }; void ethernet_protocol_packet_callback(u_char *argument, const struct pcap_pkthdr* packet_header,const u_char* packet_content) { u_short ethernet_type; struct ether_header *ethernet_protocol; u_char *mac_string; static int packet_number = 1; printf("********************************"); printf("捕获第%d个以太网数据包\n",packet_number); printf("捕获时间:\n"); printf("%s",ctime((const time_t*)&packet_header-> ts.tv_sec)); printf("数据包长度:\n"); printf("%d\n",packet_header-> len); printf("----------------以太网协议-----------\n"); ethernet_protocol = (struct ether_header *)packet_content; /*获得以太网协议内容*/ printf("以太网类型:\n"); ethernet_type = ntohs(ethernet_protocol-> ether_type); printf("%04\n",ethernet_type); switch(ethernet_type) { case 0x0800: printf("上层协议为ip协议\n"); break; case 0x0806: printf("上层协议为arp协议\n"); break; case 0x8035: printf("上层协议为rarp协议\n"); break; default :break; } printf("源以太网地址为: \n"); mac_string = ethernet_protocol-> ether_shost; printf("%02x:%02x:%02x:%02x:%02x:%02x\n",*mac_string,*(mac_string+1),*(mac_string+2),*(mac_string+3),*(mac_string+4),*(mac_string+5)); printf("目的以太网地址为: \n"); mac_string = ethernet_protocol-> ether_dhost; printf("%02x:%02x:%02x:%02x:%02x:%02x\n",*mac_string,*(mac_string+1),*(mac_string+2),*(mac_string+3),*(mac_string+4),*(mac_string+5)); printf("****************************************\n"); packet_number++; } void main() { pcap_t* pcap_handle; char error_content[pcap_errbuf_size]; char *net_interface; struct bpf_program bpf_filter; char bpf_filter_string[] = "ip"; // printf("************\n"); bpf_u_int32 net_mask; bpf_u_int32 net_ip; net_interface = pcap_lookupdev(error_content); pcap_lookupnet(net_interface, &net_ip, &net_mask,error_content); pcap_handle = pcap_open_live(net_interface,bufsiz,1,1,error_content); pcap_compile(pcap_handle, &bpf_filter, bpf_filter_string, 0, net_ip); pcap_setfilter(pcap_handle, &bpf_filter); // printf("************\n"); if(pcap_datalink(pcap_handle) != dlt_en10mb) return; // printf("************\n"); pcap_loop(pcap_handle, -1, ethernet_protocol_packet_callback,null); printf("************\n"); pcap_close(pcap_handle); } |
|
|
|
|