ip数据包的捕获与解析代码

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

// PackCaptureDlg.h:header file

#define IPV4_WERSION 4

#define IPV6_WERSION 6

#define ICMP_PACKET 1

#define IGMP_PACKET 2

#define TCP_PACKET 6

#define EGP_PACKET 8

#define UDP_packet 17

#define OSPF_PACKET 89

class CPackCaptureDlg:public CDialog

{

public:

//{{AFX_DATA(CFindHostDlg)

enum {IDO=IDO_PACKCAPTURE_DIALOG};

int m_Count;

CString m_Packet;

//}}AFX_DATA

protected:

//{{AFX_MSG(CFindHostDlg)

afx_msg void OnCapture();

//}}AFX_MSG

private:

typedef struct IP_HEAD

//IP头部结构

{

union

{

unsigned char Version;

//版本(字节前四位)

unsigned char HeadLen;

//头部长度(字节后四位)

};

unsigned char ServiceType;

//服务类型

unsigned short TotalLen;

//总长度

unsigned short Identifier;

//标识符

union

{

unsigned short Flags;

//标志位(字前三位)

unsigned short FragOffset;

//片偏移(字后13位)

};

unsigned char TimeToLive;

//生存周期

unsigned char Protocol;

//协议

unsigned short HeadChecksum;

//头部校验和

unsigned int SourceAddr;

//源IP地址

unsigned int DestinAddr;

//目的IP地址

}ip_head;

typedef struct ICMP_HEAD

//ICMP头部结构

{

unsigned char Type;

// 类型

unsigned char Code;

//代码

unsigned short HeadChecksum;

// 头部校验和

unsigned short Identifior;

//标识符

unsigned short Sequence;

//序号

}icmp_head;

};

//PackCaptureDlg.cpp :implementation file

#include "stdafx.h"

#include "PackCaptureDlg.h"

#include "PackCapture.h"

#include "winsock2.h"

#include "ws2tcpip.h"

#pragma comment(lib,"ws2_32")

#define IO_RCV ALL _WSAIOW(IOC_VENDOR,1)

void CPackCaptureDlg::OnCapture()

{

WSADATA WSAData; //建立与Socket库绑定if(WSAStartup(MAKEWORD(2,2),&WSAData)!=0)

{

MessageBox("WSAStartup初始化失败!");

return;

}

SOCKET Socket; //创建原始Socket

Socket=socket(AF_INET,SOCK_RAW,IPPROTO_IP);

if(Socket==INV ALID_SOCKET)

{

MessageBox("创建Socket失败!");

WSACleanup();

return;

}

int RecvTime=5000; //设置Socket操作选项

if(setsockopt(Socket,SOL_SOCKET,SO_RCVTIMEO,(char

*)&RecvTime,sizeof(RecvTime))==SOCKET_ERROR)

{

MessageBox("设置Socket选项失败!");

closesocket(Socket);

WSACleanup();

return;

}

char HostName[128]; //获得本地主机名称

if(gethostname(HostName,128)==SOCKET_ERROR)

{

MessageBox("获得主机名失败!");

closesocket(Socket);

WSACleanup();

return;

}

hostent* pHostent; //获得本地主机IP地址

pHostent=gethostbyname(HostNmae);

if(pHostent==NULL)

{

MessageBox("获得主机地址失败!");

closesocket(Socket);

WSACleanup();

return;

}

sockaddr_in HostAddr; //定义Socket地址结构

memset(&HostAddr,0,sizeof(HostAddr));

HostAddr.sin_family=AF_INET;

HostAddr.sin_addr.s_addr=(*(in_addr*)pHostent->h_addr).s_addr;

int nBind; //绑定Socket与网卡

nBind=bind(Socket,(PSOCKADDR)&HostAddr,sizeof(HostAddr));

if(nBind==SOCKET_ERROR)

{

MessageBox("绑定Socket失败!");

closesocket(Socket);

相关文档
最新文档