/*
 * Telnet clone which does little input/output cooking.
 * 2001 Feb 28 Junichi Uekawa <dancer@debian.org>
 * copyright 2001 Junichi Uekawa
 * See GPL version 2 or later for license.
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>

static void read_from_tcp(int * sockptr)
{
  int sock = *sockptr;
  char buf [2];
  
  while ( read (sock, buf, 1) == 1) 
    {
      fputc(buf[0], stdout);
    }
}

				/* Returns -1 on failure
				 RATIONALE: -1 is not used */
static int connect_to_host(char * stringaddress, int portnumber )
{
  struct sockaddr_in inet_address;
  struct hostent * hostinfo ;
  int sock;
    
  sock = socket (PF_INET, SOCK_STREAM, 0);
  
  inet_address.sin_family = AF_INET;
  inet_address.sin_port = htons(portnumber);
  hostinfo = gethostbyname(stringaddress);
  if (hostinfo == NULL)
    {
      return -1 ;		/* silently fail */
    }
  inet_address.sin_addr = *(struct in_addr * )hostinfo->h_addr ;

  if (connect (sock,
	       (struct sockaddr *)&inet_address,
	       sizeof (inet_address))<0)
    {
      return -1 ;		/* silently fail */
    }
  return sock;  
}

static void try_connect (char * hostname, int portnumber)
{
  int socket ;
  
  if (-1 == (socket = connect_to_host (hostname, portnumber)))
    {
      return ;			/* This port was not openable */
    }
  printf ("%i: opened\n", portnumber);
  close (socket);  
}


int main (int ac, char ** av)
{
  int portnumber ;
  int portlimit_low, portlimit_high ;
    
  printf ("scanports by Junichi Uekawa <dancer@debian.org>\nVersion 0.0.0\n");
  
  
  if (ac != 4)
    {
      fprintf(stderr, "scanports:\n\tscanports [ip address] [port number from] [port number to]");
      exit (EXIT_FAILURE);
    }

  portlimit_low = atoi ( av[2] );
  portlimit_high= atoi ( av[3] );

  for (portnumber = portlimit_low; portnumber <= portlimit_high; ++ portnumber)
    try_connect ( av[1] , portnumber );

  exit (EXIT_SUCCESS);
}
