监控数据包流量并解析
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
监控数据包流量并解析
源程序(我在课程设计时用的、献给大家)
#include "winsock2.h"
#include "ws2tcpip.h"
#include
#include
#include
#pragma comment(lib,"ws2_32")
using namespace std;
typedef struct _IP_HEADER
{
union
{
BYTE Version;
BYTE HdrLen;
};
BYTE ServiceType;
WORD TotalLen;
WORD ID;
union
{
WORD Flags;
WORD Fragoff;
};
BYTE TimeToLive;
BYTE Protocol;
WORD HdrChksum;
DWORD SrcAddr;
DWORD DstAddr;
BYTE Options;
}IP_HEADER;
int main ()
{
SOCKET sock;
WSADATA wsData;
ofstream ofs("ip.log",ios::app);
if (WSAStartup(MAKEWORD(2,2), &wsData) != 0)
{
printf("WSAStartup failed!\n");
return -1;
}
if ( ( sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP) ) ==
INVALID_SOCKET )
{
printf("create socket failed\n");
return -1;
}
BOOL flag = true;
if ( setsockopt(sock, IPPROTO_IP, IP_HDRINCL,(char*)&flag, sizeof(flag)) == SOCKET_ERROR )
{
printf("setsockopt failed!\n");
return -1;
}
char hostName[128];
if ( gethostname(hostName, 100) == SOCKET_ERROR )
{
printf("gethostname failed!\n");
return -1;
}
hostent* pHostIP;
if( ( pHostIP = gethostbyname(hostName) ) == NULL )
{
printf("gethostbyname failed\n");
return -1;
}
sockaddr_in addr_in;
addr_in.sin_addr = *(in_addr*)pHostIP->h_addr_list[0];
addr_in.sin_family = AF_INET;
addr_in.sin_port = htons(6000);
if ( bind(sock, (PSOCKADDR)&addr_in, sizeof(addr_in)) == SOCKET_ERROR )
{
printf("bind failed\n");
return -1;
}
#define IO_RCVALL _WSAIOW(IOC_VENDOR,1)
DWORD dwBufferLen[10];
DWORD dwBufferInLen = 1;
DWORD dwBytesReturned = 0;
char buffer[100];
if ( WSAIoctl(sock, IO_RCVALL, &dwBufferInLen, sizeof(dwBufferInLen),
&dwBufferLen, sizeof(dwBufferLen), &dwBytesReturned, NULL, NULL) == SOCKET_ERROR )
{
printf("ioctlsocket faild\n");
return -1;
}
printf("Analysis IP Packet !\n\n");
string s;
char * p;
char buffer1[100];
while ( true )
{
int size = recv(sock, buffer, sizeof(buffer), 0);
IP_HEADER ip = *(IP_HEADER *)buffer;
cout << "-----------------------" << endl;
s+="\n-----------------------\n";
cout << "Version: " << (ip.Version>>4) << endl;
_itoa(ip.Version>>4,buffer1,10);
s+="Version: ";
s+=buffer1;
s+="\n";
cout << "IHL: " << ( (ip.HdrLen & 0x0f) * 4) << endl;
s+="IHL:";
_itoa((ip.HdrLen & 0x0f)*4,buffer1,10);
s+=buffer1;
s+="\n";
cout << "Type of service: Priority" << (ip.ServiceType >> 5) <<
", Service" << ( (ip.ServiceType >> 1 ) & 0x0f) << endl;
s+="Type of service: Priority";
_itoa(ip.ServiceType >> 5,buffer1,10);
s+=buffer1;
s+=", Service";
_itoa((ip.ServiceType >> 1 ) & 0x0f,buffer1,10);
s+=buffer1;
s+="\n";