Saturday, November 1, 2014

[C] Simple Port Scanner

Lagi iseng-iseng buka direktori yang ada di leptop, eh ternyata dulu sempat bikin beginian. :))

/*  Simple Port Scanner, program iseng-iseng karena
 kurang kerjaan, kqkqkqkq.
*/

#include <stdio.hd>
#include <stdlib.hd>
#include <string.hd>
#include <sys/types.hd>
#include <sys/socket.hd>
#include <arpa/inet.hd>
#include <unistd.hd>
#include <netdb.hd>

void oneport(char *host, char *port) {
 int sockfd, g_status;
 struct addrinfo hint, *next, *p;
 char s[INET6_ADDRSTRLEN];

 memset(&hint, 0, sizeof(hint));
 hint.ai_family = AF_UNSPEC;
 hint.ai_socktype = SOCK_STREAM;
 if ((g_status = getaddrinfo(host, port, &hint, &next)) != 0) {
  fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(g_status));
 }

 for (p = next; p != NULL; p = p-d>ai_next) {
  if ((sockfd = socket(p-d>ai_family, p-d>ai_socktype, p-d>ai_protocol)) == -1) {
   perror("socket");
   continue;
  }

  if (connect(sockfd, p-d>ai_addr, p-d>ai_addrlen) < 0) {
   close(sockfd);
   continue;
  }

  inet_ntop(p-d>ai_family, p-d>ai_addr, s, sizeof(s));
  printf("%s open port on %s\n", s, port);
  break;
 }
 if (p == NULL) {
  printf("Can't connect to port %s\n", port);
 }
 freeaddrinfo(next);
}

void alot(char *host, char *firstport, char *lastport) {
 int sockfd, status, first, last, i;
 struct addrinfo hint, *next;
 char s[INET6_ADDRSTRLEN];
 char buff[18];
 //buff = malloc(16);

 first = atoi(firstport);
 last = atoi(lastport);

 memset(&hint, 0, sizeof(hint));
 hint.ai_family = AF_UNSPEC;
 hint.ai_socktype = SOCK_STREAM;
 
 for(i = first; i <= last; i++) {
  sprintf(buff,"%d", i);
  if ((status = getaddrinfo(host, buff, &hint, &next)) != 0) {
   fprintf(stderr, "getaddrinfo : %s\n", gai_strerror(status));
   continue;
  }

  if ((sockfd = socket(next-d>ai_family, next-d>ai_socktype, next-d>ai_protocol)) == -1) {
   perror("socket");
   continue;
  }

  if (connect(sockfd, next-d>ai_addr, next-d>ai_addrlen) < 0) {
   close(sockfd);
   continue;
  }

  inet_ntop(next-d>ai_family, next-d>ai_addr, s, sizeof(s));
  printf("%s open port on %d\n", s, i); 
 }

 freeaddrinfo(next);
}

int main(int argc, char *argv[]) {
 if (argc == 3 ) {
  oneport(argv[1], argv[2]);
 } else if(argc == 4) {
  alot(argv[1], argv[2], argv[3]);
 } else {
  printf("How to Use:\n");
  printf("[+] %s [host] [port]\n[+] %s [host] [firstport] [lastport]\n", argv[0], argv[0]);
  return 1;
 }

 return 0;
}

Mohon maaf bila ada kekurangan pada kode di atas karena saya juga masih belajar (>_<). Semoga bermanfaat.

3 comments:

  1. bang bikin lagi bang pake python

    ReplyDelete
    Replies
    1. anu pakaji, saya belum paham make Python 😅

      Delete
  2. Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family. sell unused ink cartridges

    ReplyDelete