#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define MAX_PORT 1024

int s;
struct sockaddr_in addr;
char rmt_host[100];

int skan(port)
int port;
{
 int r;
    s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s < 0) {
       printf("ERROR: socket() failed\n");
       exit(0);
    }
    addr.sin_family = PF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(rmt_host);
    r = connect(s,(struct sockaddr *) &addr, sizeof(addr));
    close(s);
    if (r==-1) {
       return (1 == 0);
    }
    return (1 == 1);
}

main(argc,argv) 
int argc;
char *argv[];
{
 int a,b,c,d,e,f;
 struct hostent *foo;
 struct servent *death;
   if (argc < 2) {
      fprintf(stderr,"\nusage: %s <host> [highest port]\n\n",argv[0]);
      fprintf(stderr, "The Death Knights Port Scanner 2.0 by Cacaio!\n");
      fprintf(stderr, "http://www.deatknights.com         Cacaio@deathknights.com\n\n");
      exit(0);
   }
   if (sscanf(argv[1],"%d.%d.%d.%d",&a,&b,&c,&d) != 4) {
      foo = gethostbyname(argv[1]);
      if (foo == NULL) {
         fprintf(stderr,"\nerror: cannot resolve host %s.\n\n",argv[1]);
         fprintf(stderr, "The Death Knights Port Scanner 2.0 by Cacaio!\n");
         fprintf(stderr, "http://www.deatknights.com         Cacaio@deathknights.com\n\n");
         exit(0);
      }
      sprintf(rmt_host,"%d.%d.%d.%d",(unsigned char )foo->h_addr_list[0][0],
              (unsigned char ) foo->h_addr_list[0][1], 
              (unsigned char ) foo->h_addr_list[0][2], 
              (unsigned char ) foo->h_addr_list[0][3]);
   } else {
      strncpy(rmt_host,argv[1],99);
   }
   if (argc > 2) {
      f = atoi(argv[2]);
   } else
      f = MAX_PORT;
      fprintf(stdout,"\nScanning host %s - TCP ports 1 through %d\n\n",rmt_host,f);
      fprintf(stdout, "The Death Knights Port Scanner 2.0 by Cacaio!\n");
      fprintf(stdout, "http://www.deatknights.com         Cacaio@deathknights.com\n\n");
      fprintf(stdout, "If appears an UNKNOWN in any port, that is because that port is not listed\n");
      fprintf(stdout, "in your /etc/services.\n\n");
   for (e =1;e<=f;e++) {
    char serv[100];
      if (skan(e)) {
         death = getservbyport(htons(e),"tcp"); 
         printf("%d (%s) is running.\n",e,(death == NULL) ? "UNKNOWN" : 
         death->s_name); 
      }
   }
}