資源簡介
用 WinPCAP 監聽并分析以太網的幀,記錄目標與源 MAC 和 IP 地址
代碼片段和文件信息
#define?HAVE_REMOTE
#include?
#include?
#include?
#pragma?comment(lib?“Packet“)
#pragma?comment(lib?“wpcap“)
#pragma?comment(lib?“WS2_32“)
/*?4字節的IP地址?*/
typedef?struct?ip_address?{
u_char?byte1;
u_char?byte2;
u_char?byte3;
u_char?byte4;
}ip_address;
typedef?struct?ip_header?{
u_char?ver_ihl;?//?Version?(4?bits)?+Internet?header?length(4?bits)
u_char?tos;?//?Type?of?service
u_short?tlen;?//?Total?length
u_short?identification;?//?Identification
u_short?flags_fo;?//?Flags?(3?bits)?+?Fragmentoffset(13?bits)
u_char?ttl;?//?Time?to?live
u_char?proto;?//?Protocol
u_short?crc;?//?Header?checksum
u_char?saddr[4];?//?Source?address
u_char?daddr[4];?//?Destination?address
u_int?op_pad;?//?Option?+?Padding
}?ip_header;
typedef?struct?mac_header?{
u_char?dest_addr[6];
u_char?src_addr[6];
u_char?type[2];
}?mac_header;
/*?UDP?首部*/
typedef?struct?udp_header?{
u_short?sport;??????????//?源端口(Source?port)
u_short?dport;??????????//?目的端口(Destination?port)
u_short?len;????????????//?UDP數據包長度(Datagram?length)
u_short?crc;????????????//?校驗和(Checksum)
}udp_header;
/*?回調函數原型?*/
void?packet_handler(u_char?*param?const?struct?pcap_pkthdr?*header?const?u_char?*pkt_data);
int?count?=?0;
struct?timeval?old_ts?=?{?00?};
time_t?timep;
struct?tm?*p;
time_t?oldtime;
int?all_len=0;
int?old_time;
main()
{
pcap_if_t?*alldevs;
pcap_if_t?*d;
int?inum;
int?i?=?0;
pcap_t?*adhandle;
char?errbuf[PCAP_ERRBUF_SIZE];
u_int?netmask;
char?packet_filter[]?=?“ip?and?udp“;
struct?bpf_program?fcode;
/*?獲得設備列表?*/
if?(pcap_findalldevs_ex(PCAP_SRC_IF_STRING?NULL?&alldevs?errbuf)?==?-1)
{
fprintf(stderr?“Error?in?pcap_findalldevs:?%s\n“?errbuf);
exit(1);
}
//findalldevs_ex(char?*source?struct?pcap_rmtauth?*auth?pcap_if_t?**alldevs?char?*errbuf??)
//source?可以是”rpcap://”,表示本地適配器;#define?PCAP_SRC_IF_STRING?“rpcap://”?
//auth:指向pcap_rmtauth結構的指針,用來保存連接到遠程主機上授權信息。在查詢本地機器時,此參數沒什么意義,可以為NULL。
//alldevs:?指向pcap_if_t結構的指針,此函數返回時,該指針被設置為所獲得的設備接口列表的第一個元素,列表的每一個元素都是Pcap_if_t結構。
//返回值:成功返回0,alldevs返回設備列表,alldevs不會為NULL。否則返回-1,那就是說系統沒有任何接口可以列舉的。出錯的消息在errbuf里面返回
/*?打印列表?*/
for?(d?=?alldevs;?d;?d?=?d->next)
{
printf(“%d.?%s“?++i?d->name);
if?(d->description)
printf(“?(%s)\n“?d->description);
else
printf(“?(No?description?available)\n“);
}
if?(i?==?0)
{
printf(“\nNo?interfaces?found!?Make?sure?WinPcap?is?installed.\n“);
return?-1;
}
printf(“Enter?the?interface?number?(1-%d):“?i);
scanf(“%d“?&inum);
if?(inum?1?||?inum?>?i)
{
printf(“\nInterface?number?out?of?range.\n“);
/*?釋放設備列表?*/
pcap_freealldevs(alldevs);
return?-1;
}
/*?跳轉到已選設備?*/
for?(d?=?alldevs?i?=?0;?inext?i++);
/*?打開適配器?*/
if?((adhandle?=?pcap_open(d->name??//?設備名
65536?????//?要捕捉的數據包的部分?
???//?65535保證能捕獲到不同數據鏈路層上的每個數據包的全部內容
PCAP_OPENFLAG_PROMISCUOUS?????????//?混雜模
評論
共有 條評論