Exercise: Capturing UDP Packets

We'll now look at a command-line tool that allows us to capture UDP packets.

Let’s get into viewing real packets.

What is tcpdump?#

tcpdump is a command-line tool that can be used to view packets being sent and received on a computer. The simplest way to run it is to simply type the following command into a terminal and hit enter. You can try this on the terminal provided at the end of this lesson!

tcpdump

Packets will start getting printed rapidly to give a comprehensive view of the traffic.

Sample Output#

However, some might not find it to be very helpful because it does not allow for a more zoomed-in and fine-grained dissection of the packets, which is the main purpose of tcpdump (it’s technically a packet analyzer). So you might want to consider using some flags to filter relevant packets out.

svg viewer
... what??

Useful tcpdump Flags

Here are some flags that you might find useful in your exploration of this tool. You can find more details about each on tcpdump’s Manpage

Saving tcpdump Output to a File with -w

Instead of having all the output print to the console, we can save it to view at a later date or to feed into another program to analyze.

svg viewer
Let's zoom into the traffic a bit
tcpdump -w filename.ext

Try using this tool in the following code executable.

The file output.pcap will have all the packets saved to it. Try running this command in the terminal below. Note that the process does not exit without a keyboard interrupt. The next flag will help us stop packet capture in a predetermined fashion.

📝 Note .pcap files are used to store the packet data of a network. Packet analysis programs such as Wireshark (think of it like tcpdump with a GUI) export and import packet captures in pcap files.

Counting Packets with -c#

This flag makes tcpdump capture a defined number of packets. Here’s how it’s used.

You can’t view the file just yet. Let’s do it next.

Printing PCAP Files With -r#

Great! Let’s actually read .pcap files now. Here’s how to do it.

We’ve gotten pretty far with this. There are plenty of other flags and arguments you could give to tcpdump to make it capture packets precisely as per your requirements.

Looking at Real UDP Packet Headers#

Here’s a script to capture and print one UDP packet.

Note that the code may time out before it actually captures a packet. We would suggest running this one on the terminal in the end of the lesson.

The -X flag just prints the payload of the packet (the data) in both hex and ASCII.

Here’s what the output is depicting.

Created with Fabric.js 1.6.0-rc.1
The command that starts tcpdump is on the first line
1 of 11

Try it Yourself!#

You can try all the commands in this terminal. Click here to go back

Terminal 1
Terminal

Click to Connect...


In the next lesson, we’ll learn about the transmission control protocol!

UDP Checksum Calculation & Why UDP?
The Transmission Control Protocol
Mark as Completed
Report an Issue