Original socket class

xiaoxiao2021-03-06  140

Remember, the main steps of this program:

1, initialize the Winsock2.dll file

BOOL CSniff :: IniNetDll () {WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD (2, 0); err = WSAStartup (wVersionRequested, & wsaData); if (! Err = 0) {/ * Tell the user that we Could Not Find A Usable * / / * Winsock DLL. * / AFXMessageBox ("Load Winsock DLL Failed!"); Return False;} Return True;

2, pick up the local IP address:

Bool csniff :: getLocalHostinfo () {char szhostname [128] = {0}; hostent * phost = null; char * pszip = null; int inum = 0; if (gethostname (szhostname, 128) == 0) {phost = gethostbyname (szHostName); if (! pHost = NULL) {pszIp = inet_ntoa (* (in_addr *) pHost-> h_addr_list [iNum]); m_ipsource = inet_addr (pszIp);} else {AfxMessageBox ( "! pHost = NULL") Return false;}}}} Return True;

3. Create an original socket

SS = new socket; * ss = socket (AF_INET, SOCK_RAW, IPPROTO_IP); if (Invalid_Socket == * SS) {dwerr = wsagetlasterror (); Sprintf (Szerr, "Error socket () =% ld", dwerr; afxMessageBox (szerr); clossoSocket (* ss); return;}

4, set the original socket parameters

int rcvtimeo = 5000; // 5 sec insteadof 45 as default if (setsockopt (* ss, SOL_SOCKET, SO_RCVTIMEO, (const char *) & rcvtimeo, sizeof (rcvtimeo)) == SOCKET_ERROR) {dwErr = WSAGetLastError (); sprintf (szErr , "Error WSAIOCTL =% LD", DWERR); AFXMessageBox (Szerr); CloseSocket (* SS); Return;}

5, bonding

sa.sin_family = AF_INET; sa.sin_port = HTONS (7000); sa.sin_addr.s_addr = m_iphostsource; if (Bind (* SS, PSOCKADDR) & sa, sizeof (sa)) == Socket_ERROR) {dwerr = wsagetlasterror () Sprintf (Szerr, "Error Bind () =% LD", DWERR); AFXMESSAGEBOX (SZERR); CloseSocket (* ss); return;} 6, set

if (SOCKET_ERROR = WSAIoctl (* ss, SIO_RCVALL, & dwBufferInLen, sizeof (dwBufferInLen), & dwBufferLen, sizeof (dwBufferLen), & dwBytesReturned, NULL, NULL)!) {TRACE ( "Success / n");} else {TRACE ( "Failed / N ");

7, start receiving

Char Buff [5102]; ZeromeMory (BUFF, 5102); int NRET = Recv (* SS, BUFF, 5102, 0); if (NRET == Socket_ERROR) {Trace ("Receive Failure!% D / N", Wsagetlasterror ));

转载请注明原文地址:https://www.9cbs.com/read-127524.html

New Post(0)