关于c++抓包解析http包的一个小程序,其他都没问题,也能正常运行,但最后会报段错误(http解析没问题)

dennis_ben 2014-07-18 05:59:39
mian.cpp代码:
#define COUNT_TIME(x,y) struct timeval x;struct timeval y;gettimeofday(&x, NULL);
#define COUNT_TIME_1(x,y) gettimeofday(&y, NULL); std::cout <<__FILE__ << '\t' << __FUNCTION__<< '\t' << ((y.tv_sec * 1000000 + y.tv_usec) - (x.tv_sec * 1000000 + x.tv_usec)) << "微秒"<< std::endl;

int main()
{
COUNT_TIME(x,y);
pcap_header pcap_head_buf;
pkt_header pkt_head_buf;
ip_header ip_head_buf;
tcp_header tcp_head_buf;
char buffer[3000];
int ch;
char *filename;

printf("please input the filename:\n");
scanf("%s",filename);
FILE *fp = fopen(filename , "rb");

getPcapFileHead(fp , pcap_head_buf);

fseek(fp, 0, SEEK_END);
long fileSize=ftell(fp);
long fpOffset=sizeof( pcap_header ) ;
while( (fseek(fp, fpOffset, SEEK_SET) == 0)&&(fpOffset<=fileSize) /* && ( !feof(fp)) ((ch=getc(fp))!=EOF) && ( fpOffset < (fileSize+1) )*/ ) //在循环中处理每一个网络帧
{
if(fpOffset==fileSize)/*||((ch=getc(fp))==EOF)(ch=getc(fp))!=EOF)*/
break;
//printf("fpOffset:%d\n fileSize:%d\n",fpOffset,fileSize);
getPktHead(fp , pkt_head_buf);
fpOffset += ( sizeof(pkt_header) + pkt_head_buf.capture_len );
//fpOffset 当前位置 +sizeof( pkt_header) +sizeof (pkt_data) ,得到下一网络帧的 offset

u_int16 framType=getFramType(fp , pcap_head_buf.linktype); //framType 标识了该帧是否为 IPV6链接
if ( framType == 0xdd86 ) //IPV6链接 , 跳过该网络帧
{
continue ;
}

else
{
getIpHead(fp , ip_head_buf);

if ( ip_head_buf.Protocol != 0x06 ) // Protocol != 0x06 表示非TCP链接 , 跳过该网络帧
{
continue ;
}
else //TCP 链接类型
{
getTcpHead(fp ,tcp_head_buf) ;
int tcp_data_size = fpOffset - ftell(fp);
// 当前位置在一个 tcp_header 后 ,fpOffset - 当前位置 得到 tcp_data 的长度
if ( tcp_data_size !=0)
{
u_int8 tempBuf[4];
std::string methodBuf;
std::string urlBuf;
std::string hostBuf;
std::string uaBuf;
std::string cookBuf;

fread(tempBuf ,4 ,1 ,fp);
fseek(fp , -4 ,SEEK_CUR);
char tcp_data_buf[3000];
memset(tcp_data_buf,0,sizeof(tcp_data_buf)/sizeof(char));

if ( ( tempBuf[0]==0x50 && tempBuf[1]==0x4f && tempBuf[2]==0x53 && tempBuf[3]==0x54 ) ||
( tempBuf[0]==0x47 && tempBuf[1]==0x45 && tempBuf[2]==0x54 )
) //两个条件分别表示 "POST " 和 " GET " ,判断成功表明 该网络帧包含了一个 HTTP  get 或者 post 链接

{


fread(tcp_data_buf , tcp_data_size ,1 ,fp );
matchHttp(tcp_data_buf , methodBuf , urlBuf , hostBuf , uaBuf ,cookBuf );
/* std::cout<<"method :"<<methodBuf<<std::endl;
std::cout<<"url :" <<urlBuf<<std::endl;
std::cout<<"host :"<<hostBuf<<std::endl;
std::cout<<"ua :"<<uaBuf<<std::endl;
std::cout<<"cookie :"<<cookBuf<<std::endl;
std::cout<<"=======*===========*=========*==========="<<std::endl;*/

}
else
continue;
}
}

}
}
COUNT_TIME_1(x,y);

fclose(fp);
//fclose(fp);
return 0;
}结果
...全文
478 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
u010763223 2016-07-13
  • 打赏
  • 举报
回复
你好,怎么解决的
dennis_ben 2014-07-22
  • 打赏
  • 举报
回复
自己解决了!
dennis_ben 2014-07-18
  • 打赏
  • 举报
回复
没有数组越界,指针也都释放了,怎么会包段错误?红帽下编译,求大牛!

4,356

社区成员

发帖
与我相关
我的任务
社区描述
通信技术相关讨论
社区管理员
  • 网络通信
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧