Author Topic: My Simple PortScanner [*nix]  (Read 1558 times)

0 Members and 1 Guest are viewing this topic.

Offline x86_64

  • Serf
  • *
  • Posts: 21
  • Cookies: 5
    • View Profile
My Simple PortScanner [*nix]
« on: September 06, 2012, 11:23:17 pm »

This is just a basic TCP Port scanner that returns a list of the ports and whether or not they are open. It should run on any *nix system. Due to adding the import "sys/types.h", it will also run on legacy BSD systems which don't include the needed definitions in "sys/socket.h". It takes the IP to be scanned as the only argument when run from the command line.


Code: [Select]
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>


int main(int argc, const char * argv[])
{
    int s, port;
    struct hostent *hostaddr;
    struct sockaddr_in servaddr;


    servaddr.sin_family = AF_INET;
    hostaddr = gethostbyname(argv[1]);


    for (port=0; port<=65535; port++)
    {
  s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  servaddr.sin_port = htons(port);


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


    return 0;
}


I compiled it with gcc 4.2.1 and tested it on a mac.

Offline Xires

  • Noob Eater
  • Administrator
  • Knight
  • *
  • Posts: 379
  • Cookies: 149
    • View Profile
    • Feed The Trolls - Xires
Re: My Simple PortScanner [*nix]
« Reply #1 on: September 06, 2012, 11:39:35 pm »
Not too bad for a very basic TCP connect scanner.  I might suggest changing 'port' to a 'register unsigned int' type and then using "++port" as increment in the 'for' loop.  If you're feeling daring(and looking for a challenge), you could try making it multithreaded.
-Xires

Offline jeefo12

  • NULL
  • Posts: 1
  • Cookies: 0
    • View Profile
Re: My Simple PortScanner [*nix]
« Reply #2 on: September 12, 2012, 06:17:16 pm »
Hi
I'm start learning C / C++
I tried this program
But it's super duper slow why ?
./output localhost
waiting almost 1 minut and Port 1 is closed
i changed 3 things
#include <unistd.h> // because i was cannot compile. close function does not declared
unsigned int port;
for (port=1; port<=65535; ++port)

Offline x86_64

  • Serf
  • *
  • Posts: 21
  • Cookies: 5
    • View Profile
Re: My Simple PortScanner [*nix]
« Reply #3 on: September 23, 2012, 10:18:53 pm »
Was tested on mac, one with real specs. I didn't bother with optimisation as it just gets the job done.