利用原始套接字(sock_raw)编写的抓取ip数据包的小程序

 

#include
#include
#include
#include
#pragma comment(lib,"Ws2_32.lib")
#define MAX_SIZE 65535
#define IO_RCVALL _WSAIOW(IOC_VENDOR,1)

struct iphead{
 union{
  unsigned char hl;
  unsigned char version;
 };
 unsigned char tos;
 unsigned short tot_len;
 unsigned short id;
 union{
  unsigned short flags;
  unsigned short off;
 };
 unsigned char ttl;
 unsigned char protocol;
 unsigned check;
 unsigned int saddr;
 unsigned int daddr;
};
void main(){
 WORD rv;
 WSADATA WSAData;
 rv=MAKEWORD(2,2);
 WSAStartup(rv,&WSAData);
 
 SOCKET sockRaw=socket(AF_INET,SOCK_RAW,IPPROTO_IP);

 BOOL optval=TRUE;
 setsockopt(sockRaw,IPPROTO_IP,IP_HDRINCL,(char *)&optval,sizeof(optval));

 char hostname[256];
 gethostname(hostname,256);

 hostent *phost;
 phost=gethostbyname(hostname);

 sockaddr_in addrRaw;
 addrRaw.sin_addr=*((in_addr *)phost->h_addr_list[0]);
 addrRaw.sin_family=AF_INET;
 addrRaw.sin_port=htons(5000);
 bind(sockRaw,(sockaddr *)&addrRaw,sizeof(sockaddr));

 DWORD dwinLength[10];
 DWORD dwin=1;
 DWORD dwReturned=0;
 WSAIoctl(sockRaw, IO_RCVALL ,&dwin,sizeof(dwin),&dwinLength,sizeof(dwinLength),&dwReturned,NULL,NULL);
 
 char buf[MAX_SIZE];
 //iphead ip;
 while(true){
  if(recv(sockRaw,buf,MAX_SIZE,0)>0){
  iphead ip=*(struct iphead *)buf;
  //if((*(in_addr *)&ip.daddr).S_un .S_addr ==addrRaw.sin_addr.S_un .S_addr ){
   cout<<"版本:"<<(ip.version>>4)<    cout<<"长度:"<    cout<<"协议:"<<(int)ip.protocol<    cout<<"源地址:"<    cout<<"目的地址:"<   //}
  }
  else
   break;
 }
 closesocket(sockRaw);
 WSACleanup();
}

你可能感兴趣的:(网络程序设计)