Advertisement
CreadPag

SCANEO DE PUERTOS EN C

May 28th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. /*
  2.     Port scanner code in c
  3. */
  4. #include<stdio.h>
  5. #include<sys/socket.h>
  6. #include<errno.h>
  7. #include<netdb.h>
  8. #include<string.h>
  9. #include<stdlib.h>
  10.  
  11. int main(int argc , char **argv)
  12. {
  13.     struct hostent *host;
  14.     int err, i , sock ,start , end;
  15.     char hostname[100];
  16.     struct sockaddr_in sa;
  17.      
  18.     //Get the hostname to scan
  19.     printf("Enter hostname or IP : ");
  20.     gets(hostname);
  21.      
  22.     //Get start port number
  23.     printf("\nEnter start port number : ");
  24.     scanf("%d" , &start);
  25.      
  26.     //Get end port number
  27.     printf("Enter end port number : ");
  28.     scanf("%d" , &end);
  29.  
  30.     //Initialise the sockaddr_in structure
  31.     strncpy((char*)&sa , "" , sizeof sa);
  32.     sa.sin_family = AF_INET;
  33.      
  34.     //direct ip address, use it
  35.     if(isdigit(hostname[0]))
  36.     {
  37.         printf("Doing inet_addr...");
  38.         sa.sin_addr.s_addr = inet_addr(hostname);
  39.         printf("Done\n");
  40.     }
  41.     //Resolve hostname to ip address
  42.     else if( (host = gethostbyname(hostname)) != 0)
  43.     {
  44.         printf("Doing gethostbyname...");
  45.         strncpy((char*)&sa.sin_addr , (char*)host->h_addr , sizeof sa.sin_addr);
  46.         printf("Done\n");
  47.     }
  48.     else
  49.     {
  50.         herror(hostname);
  51.         exit(2);
  52.     }
  53.      
  54.     //Start the port scan loop
  55.     printf("Starting the portscan loop : \n");
  56.     for( i = start ; i <= end ; i++)
  57.     {
  58.         //Fill in the port number
  59.         sa.sin_port = htons(i);
  60.         //Create a socket of type internet
  61.         sock = socket(AF_INET , SOCK_STREAM , 0);
  62.          
  63.         //Check whether socket created fine or not
  64.         if(sock < 0)
  65.         {
  66.             perror("\nSocket");
  67.             exit(1);
  68.         }
  69.         //Connect using that socket and sockaddr structure
  70.         err = connect(sock , (struct sockaddr*)&sa , sizeof sa);
  71.          
  72.         //not connected
  73.         if( err < 0 )
  74.         {
  75.             //printf("%s %-5d %s\r" , hostname , i, strerror(errno));
  76.             fflush(stdout);
  77.         }
  78.         //connected
  79.         else
  80.         {
  81.             printf("%-5d open\n",  i);
  82.         }
  83.         close(sock);
  84.     }
  85.      
  86.     printf("\r");
  87.     fflush(stdout);
  88.     return(0);
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement