Recently in the use of Wireshark grab Bag tool, the old feeling this thing with very simple, powerful, so want to understand his implementation principle, I am curious to write a basic function of the demo bar.
In fact, called grab bag tool, in fact, crawl through their network card all the IP packets, we can follow the IP packet protocol resolution not on the line.
The core of implementation is here:
1 //Create socket2Sock =sockets (Af_inet, Sock_raw, IPPROTO_IP); 3 if(Sock = =invalid_socket)4 { 5cout <<WSAGetLastError (); 6 return 0; 7 } 8 //get the native address9 Charname[ -]; Ten if(-1= = GetHostName (name,sizeof(name))) One { A closesocket (sock); -cout <<WSAGetLastError (); - return 0; the } - structHostent *phostent; -Phostent =gethostbyname (name); - //bind the address to the socket handle + sockaddr_in addr; -addr.sin_family =af_inet; +ADDR.SIN_ADDR = * (in_addr*) phostent->h_addr_list[0];//IP AAddr.sin_port =8888;//port, the IP layer port is free to fill at if(Socket_error = = bind (sock, (SOCKADDR *) &addr,sizeof(addr))) - { - closesocket (sock); -cout <<WSAGetLastError (); - return 0; - } in - //set the socket to receive all data for all NICs that flow through the bound IP, including packets received and sent toU_long Sioarg =1; +DWORD wt =0; - if(Socket_error = = WSAIoctl (sock, Sio_rcvall, &sioarg,sizeof(Sioarg), NULL,0, &wt, NULL, NULL)) the { * closesocket (sock); $cout <<WSAGetLastError (); Panax Notoginseng return 0; - } the //we only need to receive the data, so set to block Io, using the simplest IO model +U_long Bioarg =0; A if(Socket_error = = ioctlsocket (sock, Fionbio, &Bioarg)) the { + closesocket (sock); -cout <<WSAGetLastError (); $ return 0; $ } - //Start receiving data - //The IO,RECV is not returned until the data is received because it is already set to block. theG_event = CreateEvent (null,true,false,null);
Others do not say, there are development experience should be, this is a half-day out, so a lot of code did not tidy up, please forgive me. I mainly realize the function, good own use.
Here are the following:
Code Address:
http://download.csdn.net/detail/hegangle/9777070
Simulation of the Wireshark Network capture tool Implementation---C + +