网络嗅探器 sniffer 很多,不过自己做的有很多好处。window2000, XP 支持 raw socket,可以用 raw socket 构造一些特殊用途的工具.
#include
<windows.h>
#include
"winsock2.h"
#include
"IPHeader.h"
class
CRawSocket
{
SOCKET m_InSocket;
SOCKET m_OutSocket;
DWORD m_LocalIPAddress;
WORD m_LocalPort;
DWORD m_RemoteIPAddress;
WORD m_RemotePort;
int m_SendProtocal;
public
:
CRawSocket();
virtual ~CRawSocket();
void FinalIPHeader(char* pIpAndDataBuffer, int length);
void ConstructIPHeader(IPHEADER* pIpHeader, int dataLength);
void FinalTCPHeader(char* pTcpAndDataBuffer, int length);
void ConstructTCPHeader(TCPHEADER* pTcpHeader);
bool SendRawData(char* buffer, int length);
bool Receive(char* buffer, int bufferSize, int& receivedLength);
bool CreateSendSocket(LPCTSTR protocal);
bool CreateReceiveSocket(int port=-1);
DWORD GetLocalIPAddress();
void SetLocalPort(int port);
void SetRemote(DWORD remoteIP, int remotePort);
protected
:
unsigned short CalculateChecksum(char* buffer1, int len1, char* buffer2, int len2);
};
CPP
文件,在
thread
中使用
Receive
函数,可以获取网络中的数据包。
SendRawData
是发送一个自己构造数据包,仅仅是发送,不管
ack
应答,也不管
remote IP and port
。其余几个函数用于构造
Raw TCP/IP data.
#include
"stdafx.h"
#include
"RawSocket.h"
#include
<ws2tcpip.h>
#include
"IPHeader.h"
#define
SIO_RCVALL
_WSAIOW(IOC_VENDOR,1)
#define
RCVALL_OFF 0
#define
RCVALL_ON 1
#define
RCVALL_SOCKETLEVELONLY 2
CRawSocket::CRawSocket()
{
WSADATA wsaData;
char szHostName[128];
m_InSocket = INVALID_SOCKET;
m_OutSocket = INVALID_SOCKET;
if (::WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
CString s;
s.Format("Error socket()= %ld", ::GetLastError());
::AfxMessageBox(s);
}
::gethostname(szHostName, sizeof(szHostName));
HOSTENT* pHostEnt = ::gethostbyname(szHostName);
if (pHostEnt != NULL)
m_LocalIPAddress = *((DWORD*) pHostEnt->h_addr_list[