It was originally written in original words, but now I think it should not be said that it is original. In fact, the code is modified on the basis of the predecessors.
However, when I changed it, I found a lot of information and it was difficult to complete it. I used vc6. 0 has been compiled, and now the source code is sent out. This is relatively simple. It is the best for beginners, because I am also a beginner.
# Include <winsock2.h>
# Include <stdio. h> // header file used by the printf function
# Pragma comment (Lib, "ws2_32.lib ")
Void help (); // declare the help Function
Int main (INT argc, char * argv [])
{
// Declare the variable
Word wversion = makeword (2, 0); // socket version
Wsadata;
// Sockaddr_in Structure
Struct sockaddr_in sin;
Int ifromport; // start Port
Int itoport; // The end port.
Int inowport; // The port being scanned.
Char * chost; // host to be scanned
Socket s; // Save the returned value when the socket is created
Int iopenport; // number of open ports
Iopenport = 0;
// If the command line is not 4 (package portscan.exe itself), the correct usage is prompted
If (argc! = 4)
{
Help (); // 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]);
Chost = argv [1];
// 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;
}
Printf ("======== start scanning ===========/N ");
// Cyclically link the port to determine whether the port is open
For (inowport = ifromport; inowport <= itoport; inowport ++)
{
S = socket (af_inet, sock_stream, 0 );
If (S = invalid_socket)
{
Printf ("failed to create socket! /N ");
Wsacleanup ();
}
// Assign values to structure members
Sin. sin_family = af_inet;
Sin. sin_port = htons (inowport );
Sin. sin_addr.s_un.s_addr = inet_addr (chost );
// Create a connection
If (connect (S, (struct sockaddr *) & sin, sizeof (SIN) = socket_error)
{
Printf ("% s-> % d: Not open/N", chost, inowport );
Closesocket (s );
}
Else
{
Printf ("% s-> % d: Open/N", chost, inowport );
Iopenport ++;
Closesocket (s );
}
}
Printf ("========= scan results ===========/N ");
Printf ("Host: % s scan to % d ports open", chost, iopenport );
// Close the socket
Closesocket (s );
Wsacleanup ();
Return 0;
}
// The content of the Help function is as follows:
Void help ()
{
Printf ("/nportscan V1.0 by: # order tomorrow/N ");
Printf ("Usage:/N ");
Printf ("portscan.exe <targetip> <beginport> <endport>/N ");
Printf ("Example:/N ");
Printf ("portscan.exe 127.0.0.1 135 445/N ");
}
Program: