How to Code a Port Scanner in C on Linux

By | July 27, 2020

Port scanning

A port scanner is a program that checks for open network ports on a local or remote machine. For example, if a machine is running an http webserver then it has port 80 open. So by scanning for open ports on a machine, we can find what server applications are running on it.

This is useful specially in security analysis and audit. Machines that are accessible online on the internet need to be careful about what ports they have open.

In this post we shall try to code a simple port scanner in C on Linux. It will try to connect to a specified port on a machine and if the connection succeeds the port is open.

Tcp Connect Port scanner

There are many techniques for port scanning and the most basic one is tcp connect port scanning. Tcp connect port scanner works by trying to establish a connection with every port that is to be scanned.

If a connection is established then the port is open otherwise closed. This technique of port scanner is the most basic form of port scanning. However it is the slowest and not very stealthy and easily caught by firewalls or other intrusion detection systems.

Tcp connect port scanning establishes a full connection which involves a 3-way handshake between the 2 hosts. Due to this it is the slowest and consumes the maximum time. The steps involved in the 3 way handshake are

Local system ----> sends tcp syn packet -----> Remote system
Local system <---- replies with a syn+ack packet <----- Remote system
Local system ----> sends ack packet -----> Remote system

After all the 3 steps are done, the connection is fully established and ready for further communication.

In real scenarios are different port scanning technique called "tcp syn port scanning" is used. It does not establish a full 3 way handshake but establishes the connection only partially to detect the open port.

The 3 step shown above is not there in syn scanning and hence a full connection is not established and discarded midway. Therefore tcp syn scanning is much faster.

In this post we shall be coding such a tcp connect port scanner using sockets. The code samples shown are for linux. If you want to code the same thing on windows then check out the post on port scanner code in winsock.

Port scanner Code

To implement tcp connect port scanning the simple steps are

1. Create a socket
2. Run a Loop to connect with each port on the remote system. If connection is established then port open otherwise closed.

Here is the full program.

	Port scanner code in c
#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <unistd.h>

int main(int argc , char **argv)
	struct hostent *host;
	int err, i , sock ,start , end;
	char hostname[100];
	struct sockaddr_in sa;
	//Get the hostname to scan
	printf("Enter hostname or IP : ");
	//Get start port number
	printf("\nEnter start port number : ");
	scanf("%d" , &start);
	//Get end port number
	printf("Enter end port number : ");
	scanf("%d" , &end);

	//Initialise the sockaddr_in structure
	strncpy((char*)&sa , "" , sizeof sa);
	sa.sin_family = AF_INET;
	//direct ip address, use it
		printf("Doing inet_addr...");
		sa.sin_addr.s_addr = inet_addr(hostname);
	//Resolve hostname to ip address
	else if( (host = gethostbyname(hostname)) != 0)
		printf("Doing gethostbyname...");
		strncpy((char*)&sa.sin_addr , (char*)host->h_addr , sizeof sa.sin_addr);
	//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
		sock = socket(AF_INET , SOCK_STREAM , 0);
		//Check whether socket created fine or not
		if(sock < 0) 
		//Connect using that socket and sockaddr structure
		err = connect(sock , (struct sockaddr*)&sa , sizeof sa);
		//not connected
		if( err < 0 )
			//printf("%s %-5d %s\r" , hostname , i, strerror(errno));
			printf("%-5d open\n",  i);

Run the program

First compile the program using gcc. Its simple.

# gcc portscanner.c

Now run the program and provide the necessary input

# ./a.out 
Enter hostname or IP :

Enter start port number : 75
Enter end port number : 85
Doing gethostbyname...Done
Starting the portscan loop : 
80    open

So the above program scanned ports 75 to 85 on and found only port 80 to be open, which is the webserver port.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].


How to Code a Port Scanner in C on Linux
  1. terdFergusion

    for the amp& thing read [here]( what it is.

    jessechalken says : “It would be a bug in the website where you got the code. The signs have been html encoded. It’s not valid C syntax, don’t worry about it.”

    if you’re using nano, do a find and replace. hit ctrl + \ to enter the string you want replace, hit enter, and then enter the string you want to replace it with. I did this for all iterations of “&quot” and replaced with quotes “

  2. ET

    you actually should avoid using strncpy to copy or free structures, since strncpy stops on the very first zero; use memset and memcpy instead.

Leave a Reply

Your email address will not be published. Required fields are marked *