#include <winsock2.h>
#include <stdio.h>
//#include <MsTcpIp.h>
/* 加这一句才不会提示:SIO_RCVALL没有定义 */
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#pragma comment(lib, "Ws2_32")
void DecodeIPPacket(char *pData);
typedef struct _TCPHeader
{
USHORT sourcePort;
USHORT destinationPort;
ULONG sequenceNumber;
ULONG acknowledgeNumber;
ULONG dataoffset;
UCHAR flags;
USHORT windows;
USHORT checksum;
USHORT urgentPointer;
}TCPHeader, *PTCPHeader;
void main()
{
/*
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,2), wsaData) != 0)
{
return;
}
*/
char buff[1024];
int nRet;
DWORD dwValue = 1;
SOCKET sRaw = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
char szHostName[56];
SOCKADDR_IN addr_in;
struct hostent *pHost;
gethostname(szHostName, 56);;
pHost = gethostbyname((char*)szHostName);
if(pHost == NULL)
return;
addr_in.sin_family = AF_INET;
addr_in.sin_port = htons(0);
memcpy(&addr_in.sin_addr.S_un.S_addr, pHost->h_addr_list[0], pHost->h_length);
printf("binding to interface:%s\n", inet_ntoa(addr_in.sin_addr));
if(bind(sRaw, (PSOCKADDR)&addr_in, sizeof(addr_in)) == SOCKET_ERROR)
return;
if(ioctlsocket(sRaw, SIO_RCVALL, &dwValue) != 0)
return;
while(TRUE)
{
nRet = recv(sRaw, buff, 1024, 0);
if(nRet > 0)
{
DecodeIPPacket(buff);
}
}
}
void DecodeIPPacket(char *pData)
{
TCPHeader *pTCPHdr = (TCPHeader*)pData;
printf("port:%d -> %d\n", ntohs(pTCPHdr->sourcePort), ntohs(pTCPHdr->destinationPort));
}
不过怎么没有嗅到数据?奇怪。