Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // Defines implementation characteristics identified by POSIX standard.
#include <sys/types.h> // data types
#include <sys/socket.h> // Internet Protocol family
#include <netdb.h> // definitions for network database operations
#include <netinet/in.h> // Internet Protocol family
#include <time.h> // standard time functions
#define START_PORT 1
#define END_PORT 100
/*
struct sockaddr_in {
short int sin_family; // Address family
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8]; // Same size as struct sockaddr
};
*/
/*
struct hostent {
char *h_name // name of the host
char **h_aliases // A pointer to an array of pointers to alternative host names
int h_addrtype // Address type
int h_length // The length, in bytes, of the address
char **h_addr_list // network addresses for the host, terminated by a null pointer
};
*/
int main(int argc, char **argv) {
int socket_fd, port, start_port, end_port, open_ports;
long ratio;
time_t time1, time2;
struct hostent *host;
struct sockaddr_in target;
float diff;
// check for command line arguements
if (argc<2) exit(printf("Usage: %s <hostname>\n", argv[0]));
// get hostname
host = gethostbyname(argv[1]);
if (!host) exit (printf("Error looking up hostname.\n"));
// specify address family
target.sin_family = AF_INET;
target.sin_addr.s_addr = *(long *)(host->h_addr);
// get intitial clock time
time1 = time(NULL);
for (port=START_PORT; port <= END_PORT; port++) {
target.sin_port = htons(port);
// create new socket
// AF_INET = address family
// SOCK_STREAM defines socket type
//
socket_fd =socket(AF_INET,SOCK_STREAM,0);
if (socket_fd < 0) exit(printf("Error creating socket.\n"));
// check port is open
if (!connect(socket_fd,(struct sockaddr *)&target, sizeof(target))) {
open_ports++;
printf("port: %i open\n", port);
}
// clean up / close socket
if (close(socket_fd)) exit(printf("error closing socket.\n"));
}
// get final time
time2 = time(NULL);
// calculate time difference
diff = difftime(time2,time1);
printf("\nScan completed in %d seconds, %d ports open", (int)diff, (int)open_ports);
return 0;
}
I wrote this mainly for fun / experience.
Here is the problem
bash-2.05b# ./portscanner 192.168.2.5
port: 21 open
port: 22 open
port: 80 open
Scan completed in 0 seconds, 717114503 ports open
there are not 717114503 ports open,
thanks for your time