我正在开发基于Windows 7上的Windows原始套接字的数据包嗅探器。该程序从IP层捕获数据包。我在这里遇到的问题是,程序捕获所有数据包,但其中一些数据包以错误的顺序捕获,例如。对于tcp连接建立阶段,而不是以SYN,SYN-ACK,ACK顺序获取数据包,我将其作为SYN,ACK,SYN-ACK。在SYN-ACK(来自远程)之后,pgm不是在SYN-ACK之后捕获ACK,而是在SYN-ACK数据包之前获得ACK。在数据传输阶段也会发生同样的事情。程序在实际数据包之前捕获数据包的ACK包。如果我并行运行wireshark,它会正确显示。我使用Visual Studio 2005作为IDE。
#include "stdio.h"
#include "winsock2.h"
#include "ws2tcpip.h"
#include "pcap.h"
#include "MSTcpIP.h"
int main(int argc, char **argv)
{
struct in_addr addr;
int in, optval=1;
struct hostent *local;
WSADATA wsa;
char *Buffer;
//Initialise Winsock
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
printf("WSAStartup() failed.\n");
return 1;
}
//Create a RAW Socket
sniffer = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
if (sniffer == INVALID_SOCKET)
{
printf("Failed to create raw socket.\n");
return 1;
}
memset(&dest, 0, sizeof(dest));
memcpy(&dest.sin_addr.s_addr,argv[1], sizeof(argv[1]));
dest.sin_family = AF_INET;
dest.sin_port = 0;
printf("\nBinding socket to local system and port 0 ...");
if (bind(sniffer,(struct sockaddr *)&dest,sizeof(dest)) == SOCKET_ERROR)
{
printf("bind(%s) failed.\n", inet_ntoa(addr));
return 1;
}
printf("Binding successful");
//Enable this socket with the power to sniff : SIO_RCVALL is the key Receive ALL ;)
j=1;
printf("\nSetting socket to sniff...");
if (WSAIoctl(sniffer, SIO_RCVALL, &j, sizeof(j), 0, 0, (LPDWORD) &in , 0 , 0) == SOCKET_ERROR)
{
printf("WSAIoctl() failed.\n");
wprintf(L"IOCTL failed with error %d\n", WSAGetLastError());
if (WSAIoctl(sniffer, SIO_RCVALL, &j, sizeof(j), 0, 0, (LPDWORD) &in , 0 , 0) == SOCKET_ERROR) {
printf("Failed again\n");
wprintf(L"IOCTL failed again with error %d\n", WSAGetLastError());
return 1;
}
}
printf("Socket set.");
if(setsockopt(sniffer, IPPROTO_IP, IP_HDRINCL, (char *)&optval, sizeof(optval))==SOCKET_ERROR)
{
printf("failed to set socket in raw mode.");
return 0;
}
char *Buffer = (char *)malloc(65536); //Its Big!65536
do
{
mangobyte = recvfrom(sniffer , Buffer , 2000 , 0 , 0 , 0); //Eat as much as u can
if(mangobyte > 0)
{
writeCaptofile(Buffer, mangobyte); //write the captured packet to file in pcap format
}
else
{
printf( "recvfrom() failed.\n");
}
}
while ((mangobyte > 0) && (!StopSniffing));
free(Buffer);
closesocket(sniffer);
WSACleanup();
return 0;
}