代码0.docx

上传人:b****8 文档编号:27789655 上传时间:2023-07-05 格式:DOCX 页数:37 大小:23.48KB
下载 相关 举报
代码0.docx_第1页
第1页 / 共37页
代码0.docx_第2页
第2页 / 共37页
代码0.docx_第3页
第3页 / 共37页
代码0.docx_第4页
第4页 / 共37页
代码0.docx_第5页
第5页 / 共37页
点击查看更多>>
下载资源
资源描述

代码0.docx

《代码0.docx》由会员分享,可在线阅读,更多相关《代码0.docx(37页珍藏版)》请在冰豆网上搜索。

代码0.docx

代码0

一、

//捕获网络数据包的C++程序

//可以获得数据包长度、通过以太网类型确定上层协议、源以太网地址和目的以太网地址!

#include"pcap.h"

#include

#pragmacomment(lib,"wpcap.lib")

#pragmacomment(lib,"packet.lib")

#pragmacomment(lib,"ws2_32.lib")

/*以下是以太网协议格式*/

structether_header

{

u_int8_tether_dhost[6];//目的Mac地址

u_int8_tether_shost[6];//源Mac地址

u_int16_tether_type;//协议类型

};

structip_header

{

#ifdefined(WORDS_BIENDIAN)

u_int8_tip_version:

4,

ip_header_length:

4;

#else

u_int8_tip_header_length:

4,

ip_version:

4;

#endif

u_int8_tip_tos;

u_int16_tip_length;

u_int16_tip_id;

u_int16_tip_off;

u_int8_tip_ttl;

u_int8_tip_protocol;

u_int16_tip_checksum;

structin_addrip_souce_address;

structin_addrip_destination_address;

};

voidip_protool_packet_callback(u_char*argument,conststructpcap_pkthdr*packet_header,constu_char*packet_content)

{

structip_header*ip_protocol;

u_intheader_length;

u_intoffset;

u_chartos;

u_int16_tchecksum;

//MAC首部是14位的,加上14位得到IP协议首部

ip_protocol=(structip_header*)(packet_content+14);

checksum=ntohs(ip_protocol->ip_checksum);

tos=ip_protocol->ip_tos;

offset=ntohs(ip_protocol->ip_off);

printf("---------IP协议---------\n");

printf("版本号:

%d\n",ip_protocol->ip_version);

printf("首部长度:

%d\n",header_length);

printf("服务质量:

%d\n",tos);

printf("总长度:

%d\n",ntohs(ip_protocol->ip_length));

printf("标识:

%d\n",ntohs(ip_protocol->ip_id));

printf("偏移:

%d\n",(offset&0x1fff)*8);

printf("生存时间:

%d\n",ip_protocol->ip_ttl);

printf("协议类型:

%d\n",ip_protocol->ip_protocol);

switch(ip_protocol->ip_protocol)

{

case1:

printf("上层协议是ICMP协议\n");break;

case2:

printf("上层协议是IGMP协议\n");break;

case6:

printf("上层协议是TCP协议\n");break;

case17:

printf("上层协议是UDP协议\n");break;

default:

break;

}

printf("检验和:

%d\n",checksum);

printf("源IP地址:

%s\n",inet_ntoa(ip_protocol->ip_souce_address));

printf("目的地址:

%s\n",inet_ntoa(ip_protocol->ip_destination_address));

}

voidethernet_protocol_packet_callback(u_char*argument,conststructpcap_pkthdr*packet_header,constu_char*packet_content)

{

u_shortethernet_type;

structether_header*ethernet_protocol;

u_char*mac_string;

staticintpacket_number=1;

printf("----------------------------------------------\n");

printf("捕获第%d个网络数据包\n",packet_number);

printf("捕获时间:

\n");

printf("%s",ctime((consttime_t*)&packet_header->ts.tv_sec));

printf("数据包长度:

\n");

printf("%d\n",packet_header->len);

printf("---------以太网协议---------\n");

ethernet_protocol=(structether_header*)packet_content;//获得数据包内容

printf("以太网类型:

\n");

ethernet_type=ntohs(ethernet_protocol->ether_type);//获得以太网类型

printf("%04x\n",ethernet_type);

switch(ethernet_type)

{

case0x0800:

printf("上层协议是IP协议\n");break;

case0x0806:

printf("上层协议是ARP协议\n");break;

case0x8035:

printf("上层协议是RARP协议\n");break;

default:

break;

}

printf("MAC帧源地址:

\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("MAC帧目的地址:

\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));

if(ethernet_type==0x0800)//继续分析IP协议

{

ip_protool_packet_callback(argument,packet_header,packet_content);

}

printf("----------------------------------------------\n");

packet_number++;

}

intmain()

{

pcap_t*pcap_handle;//winpcap句柄

charerror_content[PCAP_ERRBUF_SIZE];//存储错误信息

bpf_u_int32net_mask;//掩码地址

bpf_u_int32net_ip;//网络地址

char*net_interface;//网络接口

structbpf_programbpf_filter;//BPF过滤规则

charbpf_filter_string[]="ip";//过滤规则字符串,只分析IPv4的数据包

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,0,error_content);//打开网络接口

pcap_compile(pcap_handle,&bpf_filter,bpf_filter_string,0,net_ip);//编译过滤规则

pcap_setfilter(pcap_handle,&bpf_filter);//设置过滤规则

if(pcap_datalink(pcap_handle)!

=DLT_EN10MB)//DLT_EN10MB表示以太网

return0;

pcap_loop(pcap_handle,10,ethernet_protocol_packet_callback,NULL);//捕获10个数据包进行分析

pcap_close(pcap_handle);

return0;

}

二、

#include "pcap.h" 

/*packethandler 函数原型*/

void packet_handler(u_char*param, const struct pcap_pkthdr*header, const u_char*pkt_data); 

main()

{

    pcap_if_t*alldevs;

    pcap_if_t*d;

    int inum;

    int i=0;

    pcap_t*adhandle;

    char errbuf[PCAP_ERRBUF_SIZE];

    /* 获取本机设备列表*/

    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING,NULL,&alldevs,errbuf)==-1)

    {

        fprintf(stderr,"Errorinpcap_findalldevs:

%s\n",errbuf);

        exit

(1);

    }

    /* 打印列表*/

    for(d=alldevs;d;d=d->next)

    {

        printf("%d.%s",++i,d->name);

        if (d->description)

            printf("(%s)\n",d->description);

        else

            printf("(Nodescriptionavailable)\n");

    }

    if(i==0)

    {

        printf("\nNointerfacesfound!

MakesureWinPcapisinstalled.\n");

        return -1;

    }

    printf("Entertheinterfacenumber(1-%d):

",i);

    scanf("%d",&inum);

    if(inum<1||inum>i)

    {

        printf("\nInterfacenumberoutofrange.\n");

        /* 释放设备列表*/

        pcap_freealldevs(alldevs);

        return -1;

    }

    /* 跳转到选中的适配器*/

    for(d=alldevs,i=0;inext,i++);

    /* 打开设备*/

    if ((adhandle=pcap_open(d->name,         // 设备名

        65536,            //65535保证能捕获到不同数据链路层上的每个数据包的全部内容

        PCAP_OPENFLAG_PROMISCUOUS,    // 混杂模式

        1000,             // 读取超时时间

        NULL,             // 远程机器验证

        errbuf            // 错误缓冲池

        ))==NULL)

    {

        fprintf(stderr,"\nUnabletoopentheadapter.%sisnotsupportedbyWinPcap\n",d->name);

        /* 释放设备列表*/

        pcap_freealldevs(alldevs);

        return -1;

    }

    printf("\nlisteningon%s...\n",d->description);

    /* 释放设备列表*/

    pcap_freealldevs(alldevs);

    /* 开始捕获*/

    pcap_loop(adhandle,0,packet_handler,NULL);

    return 0;

/* 每次捕获到数据包时,会自动调用这个回调函数*/

void packet_handler(u_char*param, const struct pcap_pkthdr*header, const u_char*pkt_data)

{

    struct tm*ltime;

    char timestr[16];

    time_tlocal_tv_sec;

    /* 将时间戳转换成可识别的格式*/

    local_tv_sec=header->ts.tv_sec;

    ltime=localtime(&local_tv_sec);

    strftime(timestr, sizeof timestr, "%H:

%M:

%S",ltime);

    printf("%s,%.6dlen:

%d\n",timestr,header->ts.tv_usec,header->len);

}

 

三、

#include

#include

#include

#include

voidusage();

voidmain(intargc,char**argv)

{

pcap_t*indesc,*outdesc;

charerrbuf[PCAP_ERRBUF_SIZE];

charsource[PCAP_BUF_SIZE];

FILE*capfile;

intcaplen,sync;

u_intres;

pcap_send_queue*squeue;

structpcap_pkthdr*pktheader;

u_char*pktdata;

floatcpu_time;

u_intnpacks=0;

/*Checkthevalidityofthecommandline*/

if(argc<=2||argc>=5)

{

usage();

return;

}

/*Retrievethelengthofthecapturefile*/

capfile=fopen(argv[1],"rb");

if(!

capfile){

printf("Capturefilenotfound!

/n");

return;

}

fseek(capfile,0,SEEK_END);

caplen=ftell(capfile)-sizeof(structpcap_file_header);

fclose(capfile);

/*Chekifthetimestampsmustberespected*/

if(argc==4&&argv[3][0]=='s')

sync=TRUE;

else

sync=FALSE;

/*Openthecapture*/

/*CreatethesourcestringaccordingtothenewWinPcapsyntax*/

if(pcap_createsrcstr(source,//variablethatwillkeepthesourcestring

PCAP_SRC_FILE,//wewanttoopenafile

NULL,//remotehost

NULL,//portontheremotehost

argv[1],//nameofthefilewewanttoopen

errbuf//errorbuffer

)!

=0)

{

fprintf(stderr,"/nErrorcreatingasourcestring/n");

return;

}

/*Openthecapturefile*/

if((indesc=pcap_open(source,65536,PCAP_OPENFLAG_PROMISCUOUS,1000,NULL,errbuf))==NULL)

{

fprintf(stderr,"/nUnabletoopenthefile%s./n",source);

return;

}

/*Opentheoutputadapter*/

if((outdesc=pcap_open(argv[2],100,PCAP_OPENFLAG_PROMISCUOUS,1000,NULL,errbuf))==NULL)

{

fprintf(stderr,"/nUnabletoopenadapter%s./n",source);

return;

}

/*ChecktheMACtype*/

if(pcap_datalink(indesc)!

=pcap_datalink(outdesc))

{

printf("Warning:

thedatalinkofthecapturediffersfromtheoneoftheselectedinterface./n");

printf("Pressakeytocontinue,orCTRL+Ctostop./n");

getchar();

}

/*Allocateasendqueue*/

squeue=pcap_sendqueue_alloc(caplen);

/*Fillthequeuewiththepacketsfromthefile*/

while((res=pcap_next_ex(indesc,&pktheader,&pktdata))==1)

{

if(pcap_sendqueue_queue(squeue,pktheader,pktdata)==-1)

{

printf("Warning:

packetbuffertoosmall,notallthepacketswillbesent./n");

break;

}

npacks++;

}

if(res==-1)

{

printf("Corruptedinputfile./n");

pcap_sendqueue_destroy(squeue);

return;

}

/*Transmitthequeue*/

cpu_time=(float)clock();

if((res=pcap_sendqueue_transmit(outdesc,squeue,sync))len)

{

printf("Anerroroccurredsendingthepackets:

%s.Only%dbytesweresent/n",pcap_geterr(outdesc),res);

}

cpu_time=(clock()-cpu_time)/CLK_TCK;

printf("/n/nElapsedtime:

%5.3f/n",cpu_time);

printf("/nTotalpacketsgenerated=%d",npacks);

printf("/nAveragepacketspersecond=%d",(int)((double)npacks/cpu_time));

printf("/n");

/*freethesendqueue*/

pcap_sendqueue_destroy(squeue);

/*Closetheinputfile*/

pcap_close(indesc);

/*

*losetheoutputadapter

*IMPORTANT:

remembertoclosetheadapter,otherwisetherewillbenoguaranteethatallthe

*packetswillbesent!

*/

pcap_close(outdesc);

return;

}

voidusage()

{

printf("/nSendcap,sendsalibpcap/tcpdumpcap

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高中教育 > 高中教育

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1