#include "stdafx.h"
#include <iostream>
#include <string>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "Ws2_32")
using namespace std;
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
//TCP数据段头
#pragma pack(1)
typedef struct _TCP
{
WORD SrcPort; // 源端口
WORD DstPort; // 目的端口
DWORD SeqNum; // 顺序号
DWORD AckNum; // 确认号
BYTE DataOff; // TCP头长
BYTE Flags; // 标志(URG、ACK等)
WORD Window; // 窗口大小
WORD Chksum; // 校验和
WORD UrgPtr; // 紧急指针
} TCP;
/#pragma pack
typedef TCP *LPTCP;
typedef TCP UNALIGNED * ULPTCP;
//IP数据段头
#pragma pack(1)
typedef struct _IP{
union
{
BYTE Version; // 版本
BYTE HdrLen; // IHL
};
BYTE ServiceType; // 服务类型
WORD TotalLen; // 总长
WORD ID; // 标识
union
{
WORD Flags; // 标志
WORD FragOff; // 分段偏移
};
BYTE TimeToLive; // 生命期
BYTE Protocol; // 协议
WORD HdrChksum; // 头校验和
DWORD SrcAddr; // 源地址
DWORD DstAddr; // 目的地址
BYTE Options; // 选项
} IP;
///#pragma pack
typedef IP * LPIP;
typedef IP UNALIGNED * ULPIP;
string GetProtocolType(int Protocol)
{
switch (Protocol)
{
case IPPROTO_ICMP : //1 /* control message protocol */
return "ICMP";
case IPPROTO_TCP : //6 /* tcp */
return "TCP";
case IPPROTO_UDP : //17 /* user datagram protocol */
return "UDP";
default:
return "UNKNOW_TYPE";
}
}
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
unsigned int iValue = 1;
int iRet = WSAStartup(MAKEWORD(2,2), &wsaData);
SOCKET sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
iRet = setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char*) &iValue, sizeof(iValue));
sockaddr_in addr;
memset((void*) &addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = inet_addr("192.168.6.141");
addr.sin_port = htons(0);
iRet = bind(sock, (struct sockaddr*) &addr, sizeof(addr));
BOOL bSniff = TRUE;
unsigned long ulBytes;
iRet = WSAIoctl(sock,SIO_RCVALL,&bSniff, sizeof(bSniff), NULL, 0, &ulBytes, NULL, NULL);
char *buf = new char[65535];
while (true)
{
memset((void*) buf, 0, 65535);
sockaddr_in sockAddr;
memset((void*) &sockAddr, 0, sizeof(sockAddr));
int iLen = sizeof(sockAddr);
iRet = recvfrom(sock, buf, 65535, 0, (struct sockaddr*) &sockAddr, &iLen);
// 对数据包进行分析,并输出分析结果
IP ip = *(IP*)buf;
TCP tcp = *(TCP*)(buf + ip.HdrLen);
string strProtocol = GetProtocolType(ip.Protocol);
cout<<"protocol: "<<strProtocol<<endl;
cout<<"IP src address: "<<inet_ntoa(*(in_addr*)&ip.SrcAddr)<<endl;
cout<<"IP tag address: "<<inet_ntoa(*(in_addr*)&ip.DstAddr)<<endl;
cout<<"TCP src port: "<<tcp.SrcPort<<endl;
cout<<"TCP tag port: "<<tcp.DstPort<<endl;
cout<<"Buf Len: "<<ntohs(ip.TotalLen)<<endl;
cout<<"-------------------------------------------------------------"<<endl;
}
delete [] buf;
closesocket(sock);
WSACleanup();
return 0;
}