How to Build a TCP Connection in Scapy

Scapy is a packet manipulation program written in Python by Philippe Biondi.

Within this article I will show you the code required to build a 3WHS within Python using Scapy.

Prevent RST

At the point you send the SYN from Scapy and the SYN-ACK is returned. Because the Linux kernel receives the SYN-ACK but didn’t send the SYN it will issue a RST. To prevent this IPtables can be used, using the syntax below,

iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP iptables -L


In order to perform a 3WHS with Scapy the following code is used.

from scapy.all import *

src = sys.argv[1]
dst = sys.argv[2]
sport = random.randint(1024,65535)
dport = int(sys.argv[3])


ACK=TCP(sport=sport, dport=dport, flags='A', seq=SYNACK.ack, ack=SYNACK.seq + 1)


To run the script above (based on you saving the script as the following syntax is used  ./ <src ip> <dst ip> <dst port>

Once run your see the following packets sent and received via a tcpdump,

[root@client ~]# tcpdump -ni any port 443 -S
14:53:14.402953 IP > S 1000:1000(0) win 8192
14:53:14.406422 IP > S 1629791522:1629791522(0) ack 10
01 win 18484
14:53:14.505963 IP > . ack 1629791523 win 8192

# = client / = server

On the server you will then see the connection established by running a netstat,

[root@server ~]# netstat -anp | grep 443 | grep EST
tcp        0      0 ::ffff:        ::ffff:   ESTABLISHED 2611/httpd
Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial