Thursday, 28 April 2011

Port Scanner in C (with Translation of Functions)


#include                                             //standard library function
#include                                      //for socket n networking functions
#include                                     //for socket function
#include                                      //for networking
#include                                          //for database......... not required........ here
#include                                            //stad library function hope u guys know abt this
#include

/* Main programs starts*/
int main(int argc, char **argv)                                   //argc
{
   int   sd;         //socket descriptor
   int    port;         //port number
   int   start;         //start port
   int    end;         //end port
   int    rval;         //socket descriptor for connect
   char    response[1024];      //to receive data
   char   *message="shell";       //data to send
   struct hostent *hostaddr;   //To be used for IPaddress
   struct sockaddr_in servaddr;   //socket structure

   if (argc < 4 )
   {
      printf("------Created By www.Softhardware.co.uk-----------\n");
      printf("--------------------------------------------------\n");
      printf("Usage: ./tscan \n");
      printf("--------------------------------------------------\n");
      return (EINVAL);
   }
   start = atoi(argv[2]);                                                           //Takes the starting port number to scan from
   end   = atoi(argv[3]);                                                          // FOr last port number that has to be scanned

   for (port=start; port<=end; port++)
   {

         //portno is ascii to int second argument

   sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); //created the tcp socket // PF_INET==family name AF_INET can also be used, SOCK_STREAM is how data bytes have to be sent, IPPRPTP_TCP== which protocol to follow, UDP or TCP

   if (sd == -1) // THis fucntion checks for the socket creation, if socket is created successful then continue else....                         print error
   {
     perror("Socket()\n");
     return (errno);
   }

   memset( &servaddr, 0, sizeof(servaddr));

   servaddr.sin_family = AF_INET;  //FAMILY NAME
   servaddr.sin_port = htons(port); //set the portno

   hostaddr = gethostbyname( argv[1] ); //get the ip 1st argument

   memcpy(&servaddr.sin_addr, hostaddr->h_addr, hostaddr->h_length);

   //below connects to the specified ip in hostaddr

   rval = connect(sd, (struct sockaddr *) &servaddr, sizeof(servaddr));
   if (rval == -1)
   {
   printf("Port %d is closed\n", port);
   close(sd);
   }
   else
   printf("Port %d is open\n",port);

   close(sd);         //socket descriptor
   }

}

[for unix platform]

........................................................

No comments:

Post a Comment