Tcp syn portscan code in C with Linux sockets

By | February 9, 2013

Port Scanning searches for open ports on a remote system. The basic logic for a portscanner would be to connect to the port we want to check. If the socket gives a valid connection without any error then the port is open , closed otherwise (or inaccessible, or filtered).

This basic technique is called TCP Connect Port Scanning in which we use something like a loop to connect to ports one by one and check for valid connections on the socket.

But this technique has many drawbacks :

1. It is slow since it establishes a complete 3 way TCP handshake. It waits for the connect() function to return.
2. It is detectable. It leaves more logs on the remote system and on any firewall that is running.

TCP-Syn Port scanning is a technique which intends to cure these two problems. The mechanism behind it is the handshaking which takes place while establishing a connection. It sends syn packets and waits for an syn+ack reply. If such a reply is received then the port is open otherwise keep waiting till timeout and report the port as closed. Quite simple! In the TCP connect technique the connect() function sends a ack after receiving syn+ack and this establishes a complete connection. But in Syn scanning the complete connection is not made.

This results in :
1. Faster scans - Partial TCP handshake is done. Only 2 packets exchanged , syn and syn+ack.
2. Incomplete connections so less detectable. But modern firewalls are smart enough to log all syn activites. So this technique is more or less detectable to same extent as TCP connect port scanning.

TCP Connect Port Scan looks like :

You -> Send Syn packet -> Host:port
Host -> send syn/ack packet -> You
You -> send ack packet -> Host

... and connection is established

TCP-Syn Port scan looks like

You -> send syn packet ->Host:port
Host -> send syn/ack or rst packet or nothing depending on the port status -> You

... stop and analyse the reply the host send :
If syn+ack reply then port open.
Closed/filtered otherwise.

Results are almost as accurate as that of TCP connection and the scan is much faster.

So the process is :

1. Send a Syn packet to a port A
2. Wait for a reply of Syn+Ack till timeout.
3. Syn+Ack reply means the port is open , Rst packet means port is closed , and otherwise it might be inaccessible or in a filtered state.


We shall code a TCP-Syn Port scanner on Linux using sockets and posix thread api.
The tools we need are :
1. Linux system with gcc and posix libraries installed
2. Wireshark for analysing the packets (Optional : for better understanding).

Program Logic

1. Take a hostname to scan.
2. Start a sniffer thread shall sniff all incoming packets and pick up those which are from hostname and are syn+ack packets.
3. start sending syn packets to ports in a loop. This needs raw sockets
4. If the sniffer thread receives a syn/ack packet from the host then get the source port of the packet and report the packet as open.
5. Keep looping as long as you have nothing else to do.
6. Quit the program if someone is calling you.


	TCP Syn port scanner code in C with Linux Sockets :)

#include&lt;stdio.h&gt; //printf
#include&lt;string.h&gt; //memset
#include&lt;stdlib.h&gt; //for exit(0);
#include&lt;errno.h&gt; //For errno - the error number
#include&lt;netdb.h&gt;	//hostend
#include&lt;netinet/tcp.h&gt;	//Provides declarations for tcp header
#include&lt;netinet/ip.h&gt;	//Provides declarations for ip header

void * receive_ack( void *ptr );
void process_packet(unsigned char* , int);
unsigned short csum(unsigned short * , int );
char * hostname_to_ip(char * );
int get_local_ip (char *);

struct pseudo_header    //needed for checksum calculation
	unsigned int source_address;
	unsigned int dest_address;
	unsigned char placeholder;
	unsigned char protocol;
	unsigned short tcp_length;
	struct tcphdr tcp;

struct in_addr dest_ip;

int main(int argc, char *argv[])
	//Create a raw socket
	int s = socket (AF_INET, SOCK_RAW , IPPROTO_TCP);
	if(s &lt; 0)
		printf (&quot;Error creating socket. Error number : %d . Error message : %s \n&quot; , errno , strerror(errno));
		printf(&quot;Socket created.\n&quot;);
	//Datagram to represent the packet
	char datagram[4096];	
	//IP header
	struct iphdr *iph = (struct iphdr *) datagram;
	//TCP header
	struct sockaddr_in  dest;
	struct pseudo_header psh;
	char *target = argv[1];
	if(argc &lt; 2)
		printf(&quot;Please specify a hostname \n&quot;);
	if( inet_addr( target ) != -1)
		dest_ip.s_addr = inet_addr( target );
		char *ip = hostname_to_ip(target);
		if(ip != NULL)
			printf(&quot;%s resolved to %s \n&quot; , target , ip);
			//Convert domain name to IP
			dest_ip.s_addr = inet_addr( hostname_to_ip(target) );
			printf(&quot;Unable to resolve hostname : %s&quot; , target);
	int source_port = 43591;
	char source_ip[20];
	get_local_ip( source_ip );
	printf(&quot;Local source IP is %s \n&quot; , source_ip);
	//Fill in the IP Header
	iph-&gt;ihl = 5;
	iph-&gt;version = 4;
	iph-&gt;tos = 0;
	iph-&gt;tot_len = sizeof (struct ip) + sizeof (struct tcphdr);
	iph-&gt;id = htons (54321);	//Id of this packet
	iph-&gt;frag_off = htons(16384);
	iph-&gt;ttl = 64;
	iph-&gt;protocol = IPPROTO_TCP;
	iph-&gt;check = 0;		//Set to 0 before calculating checksum
	iph-&gt;saddr = inet_addr ( source_ip );	//Spoof the source ip address
	iph-&gt;daddr = dest_ip.s_addr;
	iph-&gt;check = csum ((unsigned short *) datagram, iph-&gt;tot_len &gt;&gt; 1);
	//TCP Header
	tcph-&gt;source = htons ( source_port );
	tcph-&gt;dest = htons (80);
	tcph-&gt;seq = htonl(1105024978);
	tcph-&gt;ack_seq = 0;
	tcph-&gt;doff = sizeof(struct tcphdr) / 4;		//Size of tcp header
	tcph-&gt;window = htons ( 14600 );	// maximum allowed window size
	tcph-&gt;check = 0; //if you set a checksum to zero, your kernel's IP stack should fill in the correct checksum during transmission
	tcph-&gt;urg_ptr = 0;
	int one = 1;
	const int *val = &amp;one;
	if (setsockopt (s, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) &lt; 0)
		printf (&quot;Error setting IP_HDRINCL. Error number : %d . Error message : %s \n&quot; , errno , strerror(errno));
	printf(&quot;Starting sniffer thread...\n&quot;);
	char *message1 = &quot;Thread 1&quot;;
	int  iret1;
	pthread_t sniffer_thread;

	if( pthread_create( &amp;sniffer_thread , NULL ,  receive_ack , (void*) message1) &lt; 0)
		printf (&quot;Could not create sniffer thread. Error number : %d . Error message : %s \n&quot; , errno , strerror(errno));

	printf(&quot;Starting to send syn packets\n&quot;);
	int port;
	dest.sin_family = AF_INET;
	dest.sin_addr.s_addr = dest_ip.s_addr;
	for(port = 1 ; port &lt; 100 ; port++)
		tcph-&gt;dest = htons ( port );
		psh.source_address = inet_addr( source_ip );
		psh.dest_address = dest.sin_addr.s_addr;
		psh.placeholder = 0;
		psh.protocol = IPPROTO_TCP;
		psh.tcp_length = htons( sizeof(struct tcphdr) );
		memcpy(&amp;psh.tcp , tcph , sizeof (struct tcphdr));
		tcph-&gt;check = csum( (unsigned short*) &amp;psh , sizeof (struct pseudo_header));
		//Send the packet
		if ( sendto (s, datagram , sizeof(struct iphdr) + sizeof(struct tcphdr) , 0 , (struct sockaddr *) &amp;dest, sizeof (dest)) &lt; 0)
			printf (&quot;Error sending syn packet. Error number : %d . Error message : %s \n&quot; , errno , strerror(errno));
	pthread_join( sniffer_thread , NULL);
	printf(&quot;%d&quot; , iret1);
	return 0;

	Method to sniff incoming packets and look for Ack replies
void * receive_ack( void *ptr )
	//Start the sniffer thing

int start_sniffer()
	int sock_raw;
	int saddr_size , data_size;
	struct sockaddr saddr;
	unsigned char *buffer = (unsigned char *)malloc(65536); //Its Big!
	printf(&quot;Sniffer initialising...\n&quot;);
	//Create a raw socket that shall sniff
	sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
	if(sock_raw &lt; 0)
		printf(&quot;Socket Error\n&quot;);
		return 1;
	saddr_size = sizeof saddr;
		//Receive a packet
		data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &amp;saddr , &amp;saddr_size);
		if(data_size &lt;0 )
			printf(&quot;Recvfrom error , failed to get packets\n&quot;);
			return 1;
		//Now process the packet
		process_packet(buffer , data_size);
	printf(&quot;Sniffer finished.&quot;);
	return 0;

void process_packet(unsigned char* buffer, int size)
	//Get the IP Header part of this packet
	struct iphdr *iph = (struct iphdr*)buffer;
	struct sockaddr_in source,dest;
	unsigned short iphdrlen;
	if(iph-&gt;protocol == 6)
		struct iphdr *iph = (struct iphdr *)buffer;
		iphdrlen = iph-&gt;ihl*4;
		struct tcphdr *tcph=(struct tcphdr*)(buffer + iphdrlen);
		memset(&amp;source, 0, sizeof(source));
		source.sin_addr.s_addr = iph-&gt;saddr;
		memset(&amp;dest, 0, sizeof(dest));
		dest.sin_addr.s_addr = iph-&gt;daddr;
		if(tcph-&gt;syn == 1 &amp;&amp; tcph-&gt;ack == 1 &amp;&amp; source.sin_addr.s_addr == dest_ip.s_addr )
			printf(&quot;Port %d open \n&quot; , ntohs(tcph-&gt;source));

 Checksums - IP and TCP
unsigned short csum(unsigned short *ptr,int nbytes) 
	register long sum;
	unsigned short oddbyte;
	register short answer;

	while(nbytes&gt;1) {
	if(nbytes==1) {

	sum = (sum&gt;&gt;16)+(sum &amp; 0xffff);
	sum = sum + (sum&gt;&gt;16);

	Get ip from domain name
char* hostname_to_ip(char * hostname)
	struct hostent *he;
	struct in_addr **addr_list;
	int i;
	if ( (he = gethostbyname( hostname ) ) == NULL) 
		// get the host info
		return NULL;

	addr_list = (struct in_addr **) he-&gt;h_addr_list;
		//Return the first one;
		return inet_ntoa(*addr_list[i]) ;
	return NULL;

 Get source IP of system , like or

int get_local_ip ( char * buffer)
	int sock = socket ( AF_INET, SOCK_DGRAM, 0);

	const char* kGoogleDnsIp = &quot;;;
	int dns_port = 53;

	struct sockaddr_in serv;

	memset( &amp;serv, 0, sizeof(serv) );
	serv.sin_family = AF_INET;
	serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);
	serv.sin_port = htons( dns_port );

	int err = connect( sock , (const struct sockaddr*) &amp;serv , sizeof(serv) );

	struct sockaddr_in name;
	socklen_t namelen = sizeof(name);
	err = getsockname(sock, (struct sockaddr*) &amp;name, &amp;namelen);

	const char *p = inet_ntop(AF_INET, &amp;name.sin_addr, buffer, 100);


Compile and Run
$ gcc syn_portscan.c -lpthread -o syn_portscan
-lpthread option is needed to link the posix thread libraries.

Now Run

$ sudo ./syn_portscan
Socket created. resolved to
Local source IP is
Starting sniffer thread...
Starting to send syn packets
Sniffer initialising...
Port 53 open
Port 80 open


Note :

1. For the program to run correctly the local ip and the hostname ip should be resolved correctly. Wireshark should also show the TCP Syn packets as "Good" and not bogus or something.

2. The get_local_ip method is used to find the local ip of the machine which is filled in the source ip of packets. For example : if you are on a LAN or 172.x.x.x if you are directly connected to internet. The local source ip value will show this.

3. The hostname_to_ip function resolves a domain name to its ip address. It uses the gethostbyname method.

Last Updated On : 9th February 2013

Related Post

10 thoughts on “Tcp syn portscan code in C with Linux sockets

  1. Hermann Stamm-Wilbrandt

    Thank you for posting this!
    10 years after you posted this I really needed to send a single SYN packet against a port for taking over video stream of a FPV drone camera. My 1st E52 drone firmware did not respond to SYN packet at all. Until yesterday I worked around the connect() hang on that port by forking each such stealth port connect. The 2nd E52 drone I got had a different firmware, wich responded with [RST, ACK] to [SYN]. There seems to be a problem with connect() since I was not able to make it send a single SYN as needed to get drone video. Instead alwazs two SYNs were sent. This is where your “send single SYN” od your code really was needed. I added it as 1st step to pull_video.c for 1st firmware drone and was able to get rid of the fork()s that way. Now pull_video.c does capture drone camera .h264 streak thingle threaded!

    Next step is to use syn(target,port) to unlock 2nd E52 firmware video capturing as well, that where ports responded with [RST, ACK]. Thanks again,


  2. Amir

    I’m really thankful ….
    Could you send me a complete code for Fin scan ack scan syn scan connect scan
    Thank you very much.

  3. bob

    im getting this error when compiling:

    PortScanner.c: In function ‘receive_ack’:
    PortScanner.c:189:5: warning: implicit declaration of function ‘start_sniffer’ [-Wimplicit-function-declaration]
    PortScanner.c: In function ‘start_sniffer’:
    PortScanner.c:232:5: warning: implicit declaration of function ‘close’ [-Wimplicit-function-declaration]

  4. Simba

    does (struct ip) == (struct iphdr) ? and exit(0) -> exit(1)?
    in function start_sniffer(), when we break from while(1), shall we free(buffer)?

  5. Mohammad Yasin

    Hi …
    I’m really thankful ….
    I have to give a “humble” lecture about Port Scanning , it’s an activity in “Network Programming” in C and java …
    this blog is very useful, and very close to our study in this field …
    wish I can help you one day … :)

  6. ??

    I ‘m really admire your simple and logic roadmap about “Tcp Syn Portscan “.
    I desire of the project sourcecode,because a simple test.
    Could you send me ([email protected]).I’m very appreciate for that,It will be a great thanks.Thank you.

Leave a Reply to Amir Cancel reply
