ip数据包的捕获与解析实验
#include<iostream>using namespace std;
#include"winsock2.h"
#include"ws2tcpip.h"
#include"stdio.h"
#pragma comment(lib,"ws2_32")
#define IO_RCVALL _WSAIOW(IOC_VENDOR,1)
#pragma comment(lib, "ws2_32.lib")
#pragma message("Automatically linking with ws2_32.lib")
#pragma comment(lib, "advapi32.lib")
#pragma message("Automatically linking with advapi32.lib")
typedef struct IP_HEAD
{
union
{
unsigned char Version;
unsigned char HeadLen;
};
unsigned char ServiceType;
unsigned short TotalLen;
unsigned short Identifier;
union
{
unsigned short Flags;
unsigned short FragOffset;
};
unsigned char TimeToLive;
unsigned char Protocol;
unsigned short HeadChecksum;
unsigned int SourceAddr;
unsigned int DestinAddr;
unsigned char Options;
}ip_head;
int main()
{
WSADATA WSAData;
WSAStartup(MAKEWORD(2,2), &WSAData);//返回值0表示成功,通过WSAStartup函数完成对Winsock服务的初始化,使用Socket的程序在使用Socket之前必须调用WSAStartup函数
SOCKET sock=socket(AF_INET,SOCK_RAW,IPPROTO_IP);//hostent->h_addrtype表示的是主机ip地址的类型,ipv4(AF_INET),IPV6(AF_INET6)
int flag=50000;
setsockopt(sock,IPPROTO_IP,IP_HDRINCL,(char *) &flag,sizeof(flag));
char hostName[128];//主机名
gethostname(hostName,sizeof(hostName));//获取本地计算机的标准主机名,如果没有错误发生,则返回0
hostent *pHostIP;
pHostIP=gethostbyname(hostName);//用域名或主机名获取ip地址
sockaddr_in host_addr;//sockaddr_in结构用做bind,connect,recvfrom,sendto等函数的参数,指明地址信息
host_addr.sin_family=AF_INET;
host_addr.sin_port=htons(6000);//6000是端口号,是用于通信,服务器将套接字绑定到一个地址和端口号上(bind),服务器就在这个端口号上等待请求
host_addr.sin_addr=*(in_addr *)pHostIP->h_addr_list[0];//hosten->h_addr_list表示的是主机的ip地址,注意,这个地址是以网络字节序存储的。sin_addr存储ip地址
bind(sock,(PSOCKADDR)&host_addr,sizeof(host_addr));//把一个套接字与一个地址相关联
DWORD dwValue=1;
ioctlsocket(sock,IOC_VENDOR,&dwValue);
DWORD dwBufferLen[10];
DWORD dwBufferInLen=1;
DWORD dwBytesReturned=0;
WSAIoctl(sock ,IO_RCVALL ,&dwBufferInLen , sizeof(dwBufferInLen) , &dwBufferLen,sizeof(dwBufferLen),&dwBytesReturned,NULL,NULL);
char buffer[65535];
int n=3;//捕获的数据包个数
while(n>=0)
{
recv(sock,buffer,65535,0);
ip_head ip=*(ip_head *)buffer;
cout<<"版本:"<<(ip.Version>>4)<<endl;
cout<<"头部长度:"<<((ip.HeadLen &0x0f)*4)<<endl;
cout<<"服务类型:Priority"<<(ip.ServiceType>>5)<<",Service"<<((ip.ServiceType>>1)&0x0f)<<endl;
cout<<"总长度:"<<ip.TotalLen<<endl;
cout<<"标识符:"<<ip.Identifier<<endl;
cout<<"标志位:"<<((ip.Flags>>15)&0x01)<<",DF="<<((ip.Flags>>14)&0x01)<<",Mf="<<((ip.Flags>>13)&0x01)<<endl;
cout<<"片偏移:"<<(ip.FragOffset&0x1fff)<<endl;
cout<<"生存周期:"<<(int)ip.TimeToLive<<endl;
cout<<"协议:Protocol"<<(int)ip.Protocol<<endl;
cout<<"头部校验和:"<<ip.HeadChecksum<<endl;
cout<<"原地址:"<<inet_ntoa(*(in_addr *)&ip.SourceAddr)<<endl;
cout<<"目的IP地址:"<<inet_ntoa(*(in_addr *)&ip.DestinAddr)<<endl;
n--;
cout<<endl;
}
closesocket(sock);
WSACleanup();
system("pause");
}
这个程序哪里错了,望各位大神能帮帮小弟,谢谢了