A scanner C source code containing detailed comments)

Source: Internet
Author: User
# Include <stdio. h>
# Include <winsock2.h>
# Include <time. h>
# Define iport 80 // target web server port
. # Define szsign "500 13/R/nserver: Microsoft-IIS/5.0" // check whether the target has a vulnerability based on this flag.
# Pragma comment (Lib, "ws2_32.lib ")
//////////////////////////////////////// ///////////////////////////////////
//
// Define & initialize global variables
Char * sendbuff = "Get/null. Printer/N", // send the request buff
Currenttarget [52] = {0}, // store the target that the last thread will scan
Turn [4] [2] = {"-", "//", "|", "/"}; // The character indicating the progress
Int sendbufflen = strlen (sendbuff), // The length of the sent buff
Iconntimeout, // TCP connect timeout
II = 0, // Scan progress
Itotal; // total number of servers
Handle hsemaphore = NULL, // beacon kernel object handle, used to control the number of threads
Hstdout; // standard output handle of the console, which is used for progress display
Struct timeval timeout; // timeout value for connection, sending, and receiving
DWORD sleeptime; // the waiting time after each thread
/*
The sleeptime value is calculated based on the number of threads entered by the user [threadnum] and TCP connecttimeout [conntimeo. Make sure that threadnum threads are opened at the left and right of the conntimeo time. In this way, after the conntimeo time, the opened threads start to time out and exit one after another. It can continue to run stably and effectively ensure that there are threadnum threads running at the same time.
*/
//////////////////////////////////////// ///////////////////////////////////
Void showerror (char *); // function for displaying error information
Bool resetcursor (void); // reset the cursor position, called when the thread outputs
DWORD winapi showproinfo (lpvoid); // displays the progress information.
DWORD winapi scan (lpvoid); // scan Function
Void usage (char *); // helper Function
//////////////////////////////////////// ///////////////////////////////////
Int main (INT argc, char ** argv)
{
Handle hthread = NULL; // thread handle
DWORD dwthreadid; // thread ID
Struct sockaddr_in SA;
Int I,
Maxthread; // The maximum number of threads.
Wsadata WSD;
Long previuscount;
Clock_t start, end; // start time and end time of the program running
Double duration;
// Check user input parameters
If (argc! = 5)
{
Usage (argv [0]);
Return 1;
}
// Get target range
Int startnet = inet_addr (argv [1]);
Int stopnet = inet_addr (argv [2]);
Int starthost = ntohl (startnet );
Int stophost = ntohl (stopnet );
// Obtain the number of threads
Maxthread = atoi (argv [3]);
// Obtain the conn timeout value
Iconntimeout = atoi (argv [4]);
// Check the validity of parameters
If (iconntimeout> 6) | (iconntimeout <2) | (maxthread <1) | (maxthread> 500) | (stophost <starthost ))
{
Usage (argv [0]);
Return 1;
}
// Calculation time
Sleeptime = 1000 * iconntimeout/maxthread;
// Set the connection timeout value
Timeout. TV _sec = iconntimeout;
Timeout. TV _usec = 0;
_ Try
{
// Start timing
Start = clock ();
// Load the Winsock Library
If (wsastartup (makeword (1,1), & WSD )! = 0)
{
Showerror ("wsastartup ");
_ Leave;
}
// Create a beacon kernel object handle
Hsemaphore = createsemaphore (null, maxthread, maxthread, null );
If (hsemaphore = NULL)
{
Showerror ("createsemaphore ");
_ Leave;
}
// Get the standard output handle of the console
Hstdout = getstdhandle (std_output_handle );
If (hstdout = invalid_handle_value)
{
Showerror ("getstdhandle ");
_ Leave;
}
// Set the total number of targets
Itotal = stophost-starthost;
// Creation progress display thread
Hthread = createthread (null, 0, showproinfo, null, 0, & dwthreadid );
If (hthread = NULL)
{
Showerror ("1 createthread ");
_ Leave;
}
// Close the handle
Closehandle (hthread );
// Create scan threads cyclically
For (I = starthost; I <= stophost; I ++)
{
// Wait for the notification of the beacon Kernel Object
Waitforsingleobject (hsemaphore, infinite );
// Create thread to scan
Hthread = createthread (null, 0, scan, (lpvoid) I, 0, & dwthreadid );
If (hthread = NULL)
{
Showerror ("2 createthread ");
Break;
}
// Progress auto-increment 1
II ++;
// Reset the target of the last thread Scan
SA. sin_addr.s_addr = htonl (I );
Strncpy (currenttarget, inet_ntoa (SA. sin_addr), sizeof (currenttarget ));
// Take a rest)
Sleep (sleeptime );
// Close the thread handle
Closehandle (hthread );
}
// Wait until all threads end
While (1)
{
Waitforsingleobject (hsemaphore, infinite );
If (! Releasesemaphore (hsemaphore, 1, & previuscount ))
{
Showerror ("Main () releasesemaphore ");
Sleep (5000 );
Break;
}
If (previuscount = (MaxThread-1 ))
{
Printf ("/Nall done .");
Break;
}
Sleep (500 );
}
} // End of try
// Complete, clear, and close
_ Finally
{
// Timing ends
End = clock ();
// Convert the time format
Duration = (double) (end-Start)/clocks_per_sec;
// Display the time used
Printf ("/n/ncomplete. Scan % d targets use % 2.1f seconds. Speed % 0.3 g/s/N", itotal, duration, itotal/duration );
// Close the handle
Closehandle (hstdout );
Closehandle (hsemaphore );
Wsacleanup ();
}
Return 0;
}
//////////////////////////////////////// ///////////////////////////////////
//
// Echo the error message function
//
Void showerror (char * MSG)
{
MessageBox (null, MSG, "error", 0 );
// Printf ("/n % s failed: % d", getlasterror ());
}
//////////////////////////////////////// //////////////////////////////////
//
// Reset the cursor position function to scan the output result of the thread.
//
Bool resetcursor ()
{
Lele_screen_buffer_info consolescreenbufferinfo;
// Obtain the current cursor position
If (! Getconsolescreenbufferinfo (hstdout, & consolescreenbufferinfo ))
{
Showerror ("getconsolescreenbufferinfo ");
Return false;
}
// Set the X coordinate of the cursor to 0
Lelescreenbufferinfo. dwcursorposition. x = 0;
// Set the current cursor position
Setconsolecursorposition (hstdout, consolescreenbufferinfo. dwcursorposition );
Return true;
}
//////////////////////////////////////// ///////////////////////////////////
//
// Display progress information function
//
DWORD winapi showproinfo (lpvoid LP)
{
Int J, K;
Lele_screen_buffer_info consolescreenbufferinfo;
Float m;
For (j = 0; II <itotal; j ++)
{
// Take a rest ))
Sleep (sleeptime );
// Obtain the current cursor position
If (! Getconsolescreenbufferinfo (hstdout, & consolescreenbufferinfo ))
{
Showerror ("getconsolescreenbufferinfo ");
Return 1;
}
// Set the X coordinate of the percentage progress display
Lelescreenbufferinfo. dwcursorposition. x = 0;
// Set the current cursor position
Setconsolecursorposition (hstdout, consolescreenbufferinfo. dwcursorposition );
// Percentage of completed tasks
M = (II + 1) * 100.00/itotal;
// Display progress
If (II = itotal)
{
Printf ("********* 100% % wait % d seconds to exit *********/N", iconntimeout );
Break;
}
Else
{
K = J % 4;
Printf ("%-15 S % s [% d/% d] % S % 0.3g", currenttarget, turn [K], II, itotal, turn [K], M );
}
} // End of
Return 0;
}
//////////////////////////////////////// ///////////////////////////////////
//
// Scan the Function
//
DWORD winapi scan (lpvoid LP)
{
Int I = (INT) LP, ierr;
Struct sockaddr_in server;
Socket S = invalid_socket;
Char recvbuff [1024] = {0}, * PTR;
Int recvbufflen = sizeof (recvbuff );
U_long ul = 1; // The initialization value is not 0.
Fd_set R, W;
// Create socket
S = socket (af_inet, sock_stream, ipproto_tcp );
If (S = invalid_socket)
{
Printf ("/ncreate socket failed: % d", getlasterror ());
Exitprocess (1 );
}
// Fill the ADDR struct
Server. sin_family = af_inet;
Server. sin_port = htons (iport );
Server. sin_addr.s_un.s_addr = htonl (I );
_ Try
{
// Set the socket to non-lock mode. If the UL value is 0, the soocket will be set to lock mode.
Ierr = ioctlsocket (S, fionbio, (unsigned long *) & UL );
If (ierr = socket_error)
{
Resetcursor ();
Showerror ("ioctlsocket ");
Exitprocess (1 );
}
// Printf ("/n % x ioctl OK. strat conn", I );
// Connect to target
Connect (S, (struct sockaddr *) & server, sizeof (server ));
// Printf ("/n % x conn return, start select W", I );
// Set the select Parameter
Fd_zero (& W );
Fd_set (S, & W );
// Wait until connect succeeds & socket writeable
Ierr = select (0, 0, & W, 0, & timeout );
// Printf ("/n % x select W return % d", I, ierr );
// Exit if the socket is not writable after the response is returned.
If (ierr = socket_error) | (ierr = 0 ))
{
// Printf ("/n % x select return W err, exit", I );
_ Leave;
}
// Continue if the socket is writable
Else
{
// Send buff to target
// Printf ("/n % x send", I );
Ierr = Send (S, sendbuff, sendbufflen, 0 );
// Printf ("/n % x send return", I );
If (ierr = socket_error)
_ Leave;
}
// Wait for the socket to read
Fd_zero (& R );
Fd_set (S, & R );
// Printf ("/n % x start select R", I );
Ierr = select (0, & R, 0, 0, & timeout );
// Printf ("/n % x select R return % d", I, ierr );
If (ierr = socket_error) | (ierr = 0 ))
{
// Printf ("/n % x select R err, exit", I );
_ Leave;
}
Else
{
// Recv Buff from target
// Printf ("/n % x start Recv", I );
Ierr = Recv (S, recvbuff, recvbufflen, 0 );
// Printf ("/n % x Recv RET", I );
If (ierr = socket_error)
_ Leave;
}
// Verify buff
PTR = strstr (recvbuff, szsign );
If (PTR! = NULL)
{
// Call the resetcursor function before thread output.
Resetcursor ();
// Add more than one line break symbol after the output. Do not add a line break symbol before the output to avoid confusion.
Printf ("[%-15 s] Has. Printer mapped./N", inet_ntoa (server. sin_addr ));
}
}
_ Finally
{
If (! Releasesemaphore (hsemaphore, 1, null ))
Showerror ("thread releasesemaphore failed ");
Closesocket (s );
}
Return 0;
}
//////////////////////////////////////// ///////////////////////////////////
Void usage (char * proname)
{
Printf ("/n % s v0.1 only can find iis5. Printer mapped"
"/Npower by ey4s <[email] ey4s@21cn.com [/Email]> 2001.5.20"
"/Nhttp: // www.patching.net"
"/N/nusage: % S <startip> <endip> <threadnum> <conntimeo>"
"/N/nnotice"
"/N startip stopip ==> don't forgot stopip must large than startip"
"/N threadnum => thread number, please input between 1-500"
"/N conntimeo => TCP connect timeout, please input between 2-6"
"/N/nexample"
"/N % s 192.168.0.0 192.168.255.255 200 2", proname );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.