I’ve done port scanner program. It works well and accurate, but there is a problem.
It’s SUPER slow. That’s how it looks:
% ./scanner (/*means name of a program*/) 132.163.96.4 (/*desired IP address to connect*/) 12 15 (/*desired port range to scan*/)
% Running the programm...
FOR loop begin...
Connecting to the port...
12 port is closed // wait for a minute or two
FOR loop begin...
Connecting to the port...
13 port is open // instantly
FOR loop begin...
Connecting to the port...
14 port is open // instantly
FOR loop begin...
Connecting to the port...
15 port is closed // wait for a minute or two
Program is executed!
% …
What happened here is simple to understand. Socket trying to connect through unsupported/closed port, and time that it takes to server finally declines our message to join is precisely 2 or 1 minute. Ok sorted out.
How to make happen to this program skips immediately this closed port? Ideally program should scan thousands of ports in a couple of seconds, 2 to be exact.
There is the code:
// Begining of the program
// Include Files
#include <stdio.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <cstdlib>
#include <sys/select.h>
int main(int argc, char *argv[]) {
// Declare variables
struct sockaddr_in mysock;
struct hostent *hostzahod;
struct in_addr ip;
struct timeval tv;
int sock;
int bytes;
char buffer[BUFSIZ+1];
/* ----------------------If we specify ranges of ports --------------------------*/
printf("Running the programm...\n");
if (argc > 2)
{
int i, someVal, iscon;
int RangeFrom = atoi(argv[2]);
int RangeTo = atoi(argv[3]);
fd_set ReadFileDesc, WriteFileDesc, ExceptFileDesc;
for(i = RangeFrom; i <= RangeTo; i++) {
printf("FOR loop begin...\n");
sock = socket(AF_INET, SOCK_STREAM, 0);
bzero(&mysock, sizeof mysock);
tv.tv_sec = 1;
mysock.sin_family = AF_INET;
mysock.sin_port = htons(i);
inet_pton(AF_INET, argv[1], &ip);
hostzahod = gethostbyaddr((const void*)&ip, sizeof ip, AF_INET);
bcopy(hostzahod->h_addr_list[0],&mysock.sin_addr, hostzahod->h_length);
// start scanning for open ports
printf("Connecting to the port...\n");
if (connect(sock, (struct sockaddr*)&mysock, sizeof mysock) < 0) {
printf("%d port is closed\n\n", i);
close(sock);
} else {
printf("%d port is open\n\n", i);
close(sock);
} // closing FOR loop
} // closing IF loop
printf("Programm is executed!\n");
Originally program divided by two parts, so don't pay attention to "If we specify ranges of ports" comment.
#include <string>
and#include <cstdlib>
. \$\endgroup\$