Skip to content
Home » Blog » TCP Connect Scan using Python code

TCP Connect Scan using Python code

  • by

What is TCP connect scan?

A TCP connect scan is a type of port scan that uses the TCP three-way handshake to determine which ports are open on a target host.

Below is the Nmap command for the simple TCP connect scan. You can further learn about this in this link

nmap -T4 -sT scanme.nmap.org

However, to understand more about how network scanning works, you can write simple code in Python. Below is one of example how it can be done.

Python code for TCP connect scan

from scapy.all import *

def tcp_connect_scan(ip, port):

src_port = RandShort()

syn_pkt = sr1(IP(dst=ip)/TCP(sport=src_port,dport=port,flags="S"))

if(str(type(syn_pkt))=="<type 'NoneType'>"):

    print "Closed"

elif(syn_pkt.haslayer(TCP)):

    if(syn_pkt.getlayer(TCP).flags == 0x12):

        send_rst = sr(IP(dst=ip)/TCP(sport=src_port,dport=port,flags="AR"))

        print "Open"

    elif (syn_pkt.getlayer(TCP).flags == 0x14):

        print "Closed"
    else:

        print "Unknown"
else:
    print "Unknown"

WARNING/DISCLAIMER:

It’s worth noting that port scanning can be viewed as, or interpreted as, a crime. You should never run a port scanner against a website or IP address unless the owner of the server or machine you’re targeting has given you clear, written authorization. Going to someone’s house and inspecting all of their doors and windows is similar to port scanning. The only reason anyone would conduct something like this is to analyze security and weaknesses.

Related Posts

Tags:

Leave a Reply