C implemented non-blocking mode command line port scanner source code _c language

Source: Internet
Author: User
Tags clear screen get ip set socket strlen htons

The instance is a C-implemented command-line-based port-scanning code and is a non-blocking way to test connectivity to the IP and port. For everyone to use and learning convenience, has been in the code as many places as possible to add a note, I believe that to help you understand the C-port scan has a great help.

The specific function code is as follows:

#include <afxext.h> #include <winsock.h>//compile-time libraries to use #pragma comment (lib, "Wsock32.lib")//select () member Definition #def
INE ZERO (Fd_set *) 0//variable definition int maxth, Scanok, Scannum; int Portip, Hoststart, Hoststop, Startport, Endport;
Define START I and end P addresses, start and end ports long searchnum, searched; void usage (char *); Defines the display using the method function void Playx (int); Defines the status hint function void Setip2 (char *); Define set IP function void Customport (char *, char *, char *); Defines a custom scan port function void Portscannow (int); Define port scan Scan int main (int argc, char *argv[]) {wsadata wsadata;//Clear Screen system ("Cls.exe");//display version information printf ("\r\n===========
= = = Command line port scanner Portscanner V1.0 ============== "); Check input if ((ARGC < 3) | |
(argc > 4))
{//Show help hint usage (argv[0]); return-1} Detects whether the port scan if (! STRICMP (STRLWR (argv[1]), "-P") = = 0)) ({usage (argv[0)); return-1}//program initialization if (WSAStartup (Makeword), 1,1)      != 0)//If initialization error {printf ("\r\nwsatartup error");
Error information return-1; //port scan parameter conversion///If parameter is three if (argc = 3) {//Set directly IP setip2 (argv[2]);parameter is four else if (argc = = 4) {//Enter custom port scan processing customport (argv[0], argv[2], argv[3]);}//Too many parameters show help else {usage (argv[0)); Retu
rn-1;
}//Scan port start Portscannow (ARGC);
WSACleanup ();
return 0;
}//Help prompt function void usage (char * prog) {printf ("Usage:%s <Option>", prog); printf ("\r\n\n <option>:"); printf ("\r\n-p [port| Startport-endport] < hostname| ip|
Startip-endip > ");
printf ("\r\n\n Example:");
printf ("\ r \ n%s-p 192.168.0.1", prog);
printf ("\ r \ n%s-p 192.168.0.1-192.168.0.254", prog);
printf ("\ r \ n%s-p 21-80 192.168.0.1", prog);
printf ("\ r \ n%s-p 21-80 192.168.0.1-192.168.0.254\r\n", prog);
Return  }//Progress tip void Playx (int play = 0) {//progress bar char *plays[12]= {"|", "/", "-", "\", "|", "/", "-", "\", " |
",
" / ",
" - ",
" \\ ",
}; if (searchnum!= 0) {for (int i = 0; I <= 3; i + +) {printf ("=%s=%d%s Completed.
 \ r ", plays, searched * (Searchnum + 1),"% ");
Sleep (5);
} else {printf ("=%s=\r", Plays[play]);//Show Progress Sleep (10);}} Set IP
void Setip2 (char *cp) {int host; struct hostent *testhost; char *startip = "", *endip = "";
Determine if the input is 192.168.0.1-192.168.0.254 form (STRSTR (CP, "-") && strlen (cp) > && strlen (CP) < 32) {//extract end IP EndIP = STRCHR (cp, '-') + 1;//extract Start IP strncpy (startip, CP, STRLEN (CP)-strlen (STRCHR (CP, '-'));/give control to scan
Variable assignment of IP segment Hoststart = Ntohl (inet_addr (StartIP));
Hoststop = Ntohl (inet_addr (EndIP));

else {//Get the input host address testhost = gethostbyname (StartIP);
 If the address does not exist if (!testhost) {wsacleanup ();
 printf ("\r\ncan ' t get IP of:%s", CP);
Exit (-1);
}//Give control to scan IP segment variable assignment memcpy (&host, TESTHOST-&GT;H_ADDR, 4);
Hoststop = Hoststart = Ntohl (host);
}//Test thread is full void testthread (int thread =) {for (;;)
{Playx ();//test thread is full if (Maxth > Thread) sleep (m); else break;}
Return //wait thread End Function void Waitthreadend () {//Delay sleep (6000);//Show wait prompt printf ("\ r \ r \ n"); printf ("Waiting (%d) Thread end...\r
\ n ", maxth);
for (;;) {//To determine if all threads have ended if (Maxth > 0) {//Delay Waiting line program end sleep (100);
 Playx ();
Continue
else break;
printf ("\ r \ n");
Return }//Custom port scan parameter void Customport (char *cp, Char *cp2, char *cp3) {int intport; char *checker;//processing port to be scanned/scan start port variable assignment star
Tport = Atoi (CP2);
Scan end Port variable Assignment endport = atoi (CP2); Determine whether the 21-80 form if (Strstr (CP2, "-")) {Intport = atoi (Checker = STRCHR (CP2, '-') + 1); if (Intport > 0 && intp
ORT < 65536)/scan End Port variable assignment endport = intport; 
}//Port size if (Startport < 0 | | startport > 65536 | | Endport < 0 | | Endport > 65535) {usage (CP); exit (-1);}
Processing IP address setip2 (CP3); }//port scan function UINT Portscan (LPVOID port) {int addr = Portip;//Get the address to scan int sock; struct fd_set mask; struct Timeval Timeo
Ut
struct SOCKADDR_IN server;
unsigned long flag = 1;
Create a sock sock = socket (af_inet, sock_stream, 0); Create sock failure processing if (sock = = Invalid_socket) {printf ("\r\nsock error:%s", WSAGetLastError ()); maxth--; return-1;}//To Soc
K member Assignment value server.sin_family=af_inet; Server.sin_addr.s_addr = htonl (addr); The address to scan is Server.sin_port = htons (short (port));
The port to scan//Shows Progress Playx (); Call Ioctlsocket () to set socket to non-blocking mode if (ioctlsocket (sock, Fionbio, &flag)!= 0) {//Set failure handling printf ("\r\nsock error:%s", Wsag
Etlasterror ());
Closesocket (sock);
Maxth--;
return-1;
//Call Connect () connection remote host Port connect (sock, (struct sockaddr*) &server, sizeof (server)); Timeout.tv_sec = 18;
Timeout limit is 18 seconds timeout.tv_usec = 0; Fd_zero (&mask); Empty the Set mask fd_set (sock, &mask); Put sock into the collection mask//select () process scan result switch (select (sock + 1, zero, &mask, Zero, &timeout)) {case-1: {printf (
 "\r\nselect () error");
 Maxth--;
return-1;
 }//sock timeout handling case 0: {maxth-;
 Closesocket (sock);
return-1;
 } default:if (Fd_isset (sock, &mask)) {//Prohibit sock to send and receive data shutdown (sock, 0);
 Sets the output result format printf ([Found:]%s Port:%d open.\r\n, Inet_ntoa (SERVER.SIN_ADDR), Ntohs (Server.sin_port));
 Close sock closesocket (sock);
 Scanok + +;
 Maxth--;
return 1;
} return 0; //scan start main function void Portscannow (int xp) {intSport;
Char *timenow, timebuf[32]; The default scan port char *ports[32]={"21", "22", "23", "25", "53", "79", "80", "110", "111", "113", "123", "135", "139", "143", "4." 43 "," 512 "," 513 "," 514 "," 515 "," 540 "," 1080 "," 1433 "," 1521 "," 1524 "," 3306 "," 3389 "," 5631 "," 6000 "," 6112 "," 8000 "," 8. "
080 "," 12345 "//Here you can also scan your own port};
Shows the time the scan started TimeNow = _strtime (TIMEBUF);
printf ("\r\nportscan Start Time:%s\r\n\n", TimeNow);
The counter is initialized.
Maxth = 0;
Scanok = 0;
Scannum = 0;
searched = 0;
Calculate the number of ports to scan searchnum = Hoststop-hoststart +1;
if (XP = 3) Searchnum = Searchnum * 32;
if (XP = 4) Searchnum = Searchnum * (endport-startport + 1);  Port scan start for (Portip = Hoststart; Portip <= hoststop; Portip + +, Scannum + +) {//*.*.*.0 and *.*.*.255 address processing if (portip% 256) = = 0 | |
 (portip% 256) = = 255) {if (XP = 3) Searchnum = searchnum-32;
 if (XP = 4) Searchnum = Searchnum-(endport-startport + 1);
 Scannum--;
 Playx ();
Continue
if (i > one) i = 0; Default port scan//scan 192.168.0.1//scan 192.168.0.1-192.168.0.254 if (XP = 3) {for (sport = 0; Sport < Sport + +, maxth + +, searched + +) {//test when the frontline is greater than 180 testthread (
 180);
 Generate new Threading port Scan CWinThread * pthread = AfxBeginThread (Portscan,lpvoid (Atoi ((char*) ports[sport)));
 Delay sleep (120); }//From port Scan//scan-p 192.168.0.1//Scan-p 21-80 192.168.0.1-192.168.0.254 if (XP = 4) {//Compute the port to scan sport = ENDP
 Ort-startport; if (Sport > 500) {//scan from port for (sport = Startport; sport <= Endport; sport + +, maxth + +, searched + +) {Testt
  Hread (2000);
  Generate new Threading port Scan CWinThread * pthread = AfxBeginThread (Portscan, LPVOID (sport));
 Delay sleep (10); } else {//scanned from port for (sport = Startport; sport <= Endport; sport + +, maxth + +, searched + +) {//test when the line is greater than 2
  Testthread (250);
  Generate new Threading port Scan CWinThread * pthread = AfxBeginThread (Portscan, LPVOID (sport));
  Delay sleep (100);
 Playx ();
Wait for all threads to end waitthreadend ();
Display port scan end time TimeNow = _strtime (TIMEBUF); printf ("\r\nportscan End TIME:%s ", TimeNow); printf ("\r\nscan%d Hosts completed.")
Open%d ports!\r\n ", Scannum, Scanok);

 }

To test the port scanner, you can use the following connection test code to test, the source code is as follows:

/* This function implementation to determine whether the M_server M_port port can be connected, timeout limit of ntimeout seconds * * * BOOL connecttest (char * m_server,int m_port) {struct hostent* h 
    OST = NULL; 
    struct sockaddr_in saddr; 
    unsigned int s = 0; 
    BOOL ret; 
    time_t start; 
    int error; 
    Host = gethostbyname (M_server); 

    if (host==null) return FALSE; 
    saddr.sin_family = af_inet; 
    Saddr.sin_port = htons (M_port); 
    SADDR.SIN_ADDR = * ((struct in_addr*) host->h_addr); 
    if ((S=socket (af_inet, Sock_stream, 0)) <0) {return FALSE; 

    } fcntl (S,F_SETFL, O_nonblock); if (Connect (s, (struct sockaddr*) &saddr, sizeof (saddr)) = = 1) {if (errno = = einprogress) {//It is in the Conn 
            ECT process struct Timeval TV; 
            Fd_set Writefds; 
            Tv.tv_sec = M_ntimeout; 
            tv.tv_usec = 0; 
            Fd_zero (&writefds); 
            Fd_set (S, &writefds); if (select (S+1,NULL,&AMP;WRITEFDS,NULL,&AMP;TV) >0) {int Len=sizeof (int); 
                The following sentence must be focused on the firewall getsockopt (s, Sol_socket, So_error, &error, &len); 
                if (error==0) ret=true; 
            else Ret=false; 
    }else ret=false;//timeout or error happen}else Ret=false; 
    else ret=true; 
    Close (s); 
return ret; }

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.