生物学研究的热点:为什么我用raw socket编写出来的数据包分析程序,得出的数据都是乱码?怎样才能得到正确的数据包数据?

来源:百度文库 编辑:神马品牌网 时间:2024/04/29 01:25:49
源程序如下(限于篇幅,我把截获数据包的程序省了):
请大家指点,一起帮忙讨论讨论,谢了
#include <iostream.h>
#include <string.h>
#include <winsock2.h>
#include "mstcpip.h"

#pragma comment(lib, "ws2_32.lib")

//定义IP首部
typedef struct ip_hdr
{
unsigned char h_verlen;
unsigned char tos;
unsigned short total_len;
unsigned short ident;
unsigned short frag_and_flags;
unsigned char ttl;
unsigned char proto;
unsigned short checksum;
unsigned int sourceIP;
unsigned int destIP;
}IP_HEADER;

//定义TCP首部
typedef struct tcp_hdr
{
USHORT th_sport;
USHORT th_dport;
unsigned int th_seq;
unsigned int th_ack;
unsigned char th_lenres;
unsigned char th_flag;
USHORT th_win;
USHORT th_sum;
USHORT th_urp;
}TCP_HEADER;

//定义协议结构
typedef struct protocol
{
int proto;
char* prototext;
}PROTOCOL;

//定义协议数组
PROTOCOL protoStr[3]={{IPPROTO_IP, "IP"}, {IPPROTO_TCP, "TCP"}, {IPPROTO_UDP, "UDP"}};

char* GetProtocolName(unsigned char proto); //获取协议名称

void DecoPacket(char *buffer)
{
IP_HEADER *ipHeader;//IP_HEADER型指针
TCP_HEADER *tcpHeader;//TCP_HEADER型指针
in_addr inAddr;
char* pData=NULL;

ipHeader=(IP_HEADER*)buffer;
tcpHeader=(TCP_HEADER*)(buffer+sizeof(IP_HEADER));

char* protoname=GetProtocolName(ipHeader->proto);
cout<<"协议类型:\t"<<protoname<<endl;

inAddr.s_addr = ipHeader->sourceIP;
cout<<"来源地址:\t"<<inet_ntoa(inAddr)<<endl;

inAddr.s_addr = ipHeader->destIP;
cout<<"目的地址:\t"<<inet_ntoa(inAddr)<<endl;

cout<<"来源端口:\t"<<ntohs(tcpHeader->th_sport)<<endl;
cout<<"目的端口:\t"<<ntohs(tcpHeader->th_dport)<<endl;

pData=(char*)(buffer+sizeof(IP_HEADER)+sizeof(TCP_HEADER));
cout<<"传送数据:\t"<<pData<<endl;
}

//获取协议名称
char* GetProtocolName(unsigned char proto)
{
BOOL getOK;

for(int i=0; i<3; i++)
{
if(protoStr[i].proto == proto)
{
getOK=true;
break;
}
}
if(getOK)
return(protoStr[i].prototext);
else
return("");
}
多谢了,可以发到我的邮箱吗?我的邮箱是:tufei8438@sina.com

不进行调试,光看源码很难看出问题的,出乱码可能是截取的地方没写好吧,原始套接字的程序源码我有,可以和我联系。