Skip to content

Instantly share code, notes, and snippets.

@pbrisbin
Created June 26, 2011 00:26
Show Gist options
  • Save pbrisbin/1047079 to your computer and use it in GitHub Desktop.
Save pbrisbin/1047079 to your computer and use it in GitHub Desktop.
simple port scanner
/* Original author: Vikraman (vh4x0r @ Freenode) <vikraman.choudhury@gmail.com> */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAXPORT 65535
static void die(char *msg) { /* {{{ */
perror(msg);
exit(EXIT_FAILURE);
} /* }}} */
static int is_open(struct addrinfo *servinfo, int port) { /* {{{ */
int sockfd, ret = 0;
((struct sockaddr_in *)servinfo->ai_addr)->sin_port = htons(port);
if ((sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) < 0)
return ret;
if ((connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen)) == 0) {
ret = 1;
}
close (sockfd);
return ret;
} /* }}} */
static void scan(struct addrinfo *servinfo) { /* {{{ */
struct addrinfo *p;
int port;
int nopen = 0;
int openports[MAXPORT + 1];
for (p = servinfo; p; p = p->ai_next) {
for (port = 1; port <= MAXPORT; port++) {
if (!openports[port]) {
if (is_open(p, port)) {
nopen++;
openports[port] = 1;
printf(" port %-5i is open\n", port);
}
}
}
}
printf("\n%i ports closed or filtered.\n", MAXPORT - nopen);
} /* }}} */
int main (int argc, char *argv[]) {
struct addrinfo *servinfo;
struct addrinfo hints;
if (argc != 2) {
fprintf(stderr, "usage: scanner <host>\n");
exit(EXIT_FAILURE);
}
printf("scanning host %s...\n\n", argv[1]);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(argv[1], NULL, &hints, &servinfo) != 0)
die("error getting address info");
scan(servinfo);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment