TCP Connect Port Scanner with Linux Sockets (BSD)
TCP Connect Port Scanner works by trying to establish a connection with every port that is being scanned. If a connectio is established then the port is open otherwise closed.
The steps are simple :
1. Create a socket
2. Run a Loop to connect with each port on the remote system ; if connection established then port open otherwise closed.
Code :
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<errno.h>
#include<netdb.h>
#include<string.h>
int main(int argc , char **argv)
{
struct hostent *host;
int err, i , net ,start , end;
char hostname[100];
struct sockaddr_in sa;
//Get the hostname to scan
printf("Enter hostname or IP : ");
gets(hostname);
//Get start port number
printf("nEnter start port number : ");
scanf("%d" , &start);
//Get end port number
printf("nEnter end port number : ");
scanf("%d" , &end);
//Initialise the sockaddr_in structure
strncpy((char*)&sa , "" , sizeof sa);
sa.sin_family = AF_INET;
if(isdigit(hostname[0]))
{
printf("Doing inet_addr...");
sa.sin_addr.s_addr = inet_addr(hostname);
printf("Donen");
}
else if((host = gethostbyname(hostname))!=0)
{
printf("Doing gethostbyname...");
strncpy((char*)&sa.sin_addr , (char*)host->h_addr , sizeof sa.sin_addr);
printf("Donen");
}
else
{
herror(hostname);
exit(2);
}
//Start the port scan loop
printf("Starting the portscan loop : n");
for(i=start ; i<=end ; i++)
{
//Fill in the port number
sa.sin_port = htons(i);
//Create a socket of type internet
net = socket(AF_INET , SOCK_STREAM , 0);
//Check whether socket created fine or not
if(net < 0)
{
perror("nSocket");
exit(1);
}
//Connect using that socket and sockaddr structure
err = connect(net , (struct sockaddr*)&sa , sizeof sa);
if(err<0)
{
printf("%s %-5d %sr" , hostname , i, strerror(errno));
fflush(stdout);
}
else
{
printf("%s %-5d accepted. n", hostname , i);
//Now shutdown the read and write operations on this socket
if(shutdown(net , SHUT_RDWR) < 0)
{
//Print error with error message mapped from err_no
perror("nShutdown");
exit(1);
}
}
close(net);
}
printf("r");
fflush(stdout);
return(0);
}
Popularity: 3% [?]















