My original single-thread scanner (multithreading)

Source: Internet
Author: User

// Portscan. cpp: defines the entry point for the console application.
//

/// =================================================== ==========================================================
/// Portscan-Port Scanner
///
/// 2005-7-8 16:49:52
/// =================================================== ==========================================================
# Include <winsock2.h>
# Include <stdio. h> // header file used by the printf function
# Pragma comment (Lib, "ws2_32.lib ")

Void help ();
DWORD winapi scanthread (lpvoid LP );
Void reportapierror ();

// Save the scan Host IP address and port structure
Typedef struct {
Char hostip [17];
Int scanport;
} Hoststruct;

Long lportopen = 0; // count the number of open ports

Int main (INT argc, char * argv [])
{
Word wversion = makeword (2, 0); // socket version
Wsadata;
Int ifromport; // start Port
Int itoport; // The end port.
Int inowport; // The port being scanned.
Int iportcount; // The total number of ports.

// If the command line is not 4 (package portscan.exe itself), the correct usage is prompted
If (argc! = 4)
{
Help ();
Return-1;
}

// Save the Start port and end port entered by the user for scanning. Because the user inputs the char type, convert it to the int type first.
Ifromport = atoi (argv [2]);
Itoport = atoi (argv [3]);

// Judge the port entered by the user
If (ifromport> itoport | ifromport <0 | ifromport> 65535 | itoport <0 | itoport> 65535)
{
Printf ("the starting port cannot be greater than the ending port, and the range is 1-65535! /N ");
Return 0;
}

If (wsastartup (wversion, & wsadata ))
{
Printf ("initialization failed! ");
Return-1;
}

// Total number of ports to be scanned
Iportcount = itoport-ifromport + 1;
Printf ("port range: % d-> % d, % d in total./N", ifromport, itoport, iportcount );
Printf ("/n ======= start scanning ===========/N ");

// Number of thread handles created based on the number of ports
Handle * hthreads = new handle [iportcount];
Zeromemory (hthreads, sizeof (handle) * iportcount );
//
// Create a thread parameter structure pointer based on the number of ports. It is used only to record the structure pointer for the main thread to release dynamic memory.
//
Hoststruct ** pscanhosts = new hoststruct * [iportcount];
Zeromemory (pscanhosts, sizeof (hoststruct *) * iportcount );

// Cyclically connect the port to determine whether the port is open
Int ithreadcount = 0; // number of successfully created threads
Int iparamcount = 0; // thread handle array index
For (iparamcount = 0, inowport = ifromport; inowport <= itoport; iparamcount ++, inowport ++)
{
// Provide a separate thread parameter for a separate thread. This parameter cannot be allocated on a local stack.
Pscanhosts [iparamcount] = new hoststruct;
Strcpy (pscanhosts [iparamcount]-> hostip, argv [1]);
Pscanhosts [iparamcount]-> scanport = inowport;
Handle hthread;
Hthread = createthread (null, null, scanthread, pscanhosts [iparamcount], null, null );
If (hthread = NULL)
{
Reportapierror ();
Continue;
}
Else
Hthreads [ithreadcount ++] = hthread; // only count normal running threads
}

Printf ("the thread has been created! /N ");

//
// This step is required to wait for the thread to finish execution. Otherwise, the allocated dynamic memory will be released too early and the parameter data will be abnormal during thread execution.
//
// Waitformultipleobjects can wait for a maximum of 64 maximum_wait_objects objects.
//
For (INT igroup = 0; ithreadcount> 0; igroup ++, ithreadcount-= maximum_wait_objects)
{
DWORD res = waitformultipleobjects (
Ithreadcount> maximum_wait_objects? Maximum_wait_objects: ithreadcount,
Hthreads + igroup * maximum_wait_objects,
True,
Infinite );

If (RES = wait_failed)
{
Reportapierror ();
Continue;
}
}
Printf ("Scan completed! /N ");
Printf ("Total open ports: % LD/N", lportopen );
 
// Release all dynamically allocated memory
Delete [iportcount] hthreads;
For (int ii = 0; II <iportcount; II ++)
{
Delete pscanhosts [II];
}
Delete [iportcount] pscanhosts;
Wsacleanup ();

Return 0;
}

// ================================================ ==========================================================
// Thread Functions
// 2005-7-8 16:52:41
// ================================================ ==========================================================
DWORD winapi scanthread (lpvoid LP)
{
Struct sockaddr_in sin; // addr_in Structure
Socket s; // Save the returned value when the socket is created

// Pass the parameter to the hoststruct structure pointer
Hoststruct * lpscanhost = (hoststruct *) LP;

S = socket (af_inet, sock_stream, 0 );
If (S = invalid_socket)
{
Printf ("failed to create socket! /N ");
// Wsacleanup (); // This is not what you should do here
}

// Assign values to structure members
Sin. sin_family = af_inet;
Sin. sin_port = htons (lpscanhost-> scanport );
Sin. sin_addr.s_un.s_addr = inet_addr (lpscanhost-> hostip );

// Establish a connection
If (connect (S, (struct sockaddr *) & sin, sizeof (SIN) = socket_error)
{
Printf ("% s-> % d: Not open/N", lpscanhost-> hostip, lpscanhost-> scanport );
// Closesocket (s); // not necessary!
}
Else
{
Printf ("% s-> % d: Open/N", lpscanhost-> hostip, lpscanhost-> scanport );
// Iportopen ++;
Interlockedincrement (& lportopen );
Closesocket (s );
}
 
Return 0;
}

// The content of the Help function is as follows:
Void help ()
{
Printf ("/nportscan V1.0 by: # order tomorrow/N ");
Printf ("/nportscan V1.1 by: meteor135 smith_135@163.com/N ");
Printf ("Usage:/N ");
Printf ("portscan.exe <targetip> <beginport> <endport>/N ");
Printf ("Example:/N ");
Printf ("portscan.exe 127.0.0.1 1 445/N ");
}

// ================================================ ==========================================================
// Report API errors
// 2005-7-8 16:52:19
// ================================================ ==========================================================
Void reportapierror ()
{
Lpvoid lpmsgbuf;
If (! Formatmessage (
Format_message_allocate_buffer |
Format_message_from_system |
Format_message_ignore_inserts,
Null,
Getlasterror (),
Makelangid (lang_neutral, sublang_default), // default language
(Lptstr) & lpmsgbuf,
0,
Null ))
{
// Handle the error.
Return;
}
// Display the string.
Printf ("% s/n", lpmsgbuf );
// Free the buffer.
Localfree (lpmsgbuf );
}

Thank you! Meteor135 (Meteor Shower)Improve my program. Now the multi-threaded scanner is fast, but there are still some minor problems. If there is a better version, I will send it to you for research.

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.