TCP allows for the transmission of information in both directions. This means that computer systems that communicate over TCP can send and receive data at the same time, similar to a telephone conversation.
The protocol uses segments (packets) as the basic units of data transmission. In addition to the payload, segments can also contain control information and are limited to 1,500 bytes.
We will use this post to learn how to capture TCP packets with Tcpdump command.
Create a TCP connection with Python code
We can use this Python code to connect port 180 on google.com. This will not work as this port is not open. At the same time, we can open a new terminal to check the state of TCP connection. After some time, the connection will be failed.
If we see SYN_SENT connections, this usually means that there is a firewall problem between sender and receiver. The TCP 3-way handshake can not be completed.
# python -c 'import socket;client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);client_socket.connect(("google.com", 180))'
# netstat -anpl|grep :180 tcp 0 1 10.254.222.37:40896 220.127.116.11:180 SYN_SENT 17998/python
Capture TCP packets with Tcpdump
We can use this command to filter this TCP packet with tcpdump.
- # tcpdump –i any TCP port 180 –XAvvv
To briefly explain the options we passed to it:
-i any means all the interfaces
tcp means that only tcp packets will be captured. Other types of packets we might capture could be udp or icmp for example.
-vvv just gives us more verbose output
-X prints out the data in the Tcp packets in ASCII as well as hex. If we just wanted the latter we could use the -x option
Capture TCP packets and other filters with Tcpdump
One of the best features of tcpdump is that we can filter out exactly the traffic we want to see.
tcpdump -i interface tcp and host 10.1.1.1
tcpdump -i interface tcp and port 53
tcpdump -i interface tcp or dst host 10.1.1.1
tcpdump -i interface tcp or src port 53
tcpdump -n ‘dst host 10.10.150.20 and (tcp port 80 or tcp port 443)’