- Shell Scripting
- Docker in Linux
- Kubernetes in Linux
- Linux interview question
Traceroute Implementation on Python
In Network information discovery, the traceroute tool is a fundamental utility in a Linux environment. Although the tool is already developed for the command line utility, we can still make our own Traceroute tool using Python language. We will explore the fundamentals of ICMP (Internet Control Message Protocol) and utilize Python's socket programming. So in this article, we will see the detailed implementation of the Traceroute tool in Python Language.
What is Traceroute?
Traceroute is a command-line utility in Linux that provides a detailed analysis of the route data packets take from the source to a specified destination on a network. By sending a series of Internet Control Message Protocol (ICMP) or User Datagram Protocol (UDP) packets with increasing Time-to-Live (TTL) values, Traceroute reveals the successive network hops, or routers, that the packets traverse. As each packet reaches its TTL limit, an ICMP " Time Exceeded " message is sent back, allowing Traceroute to identify and display the IP addresses and response times of each intermediary node. This information is invaluable for diagnosing network issues, assessing latency, and understanding the specific path data follows across the Internet.
Why to use the Traceroute Tool?
A Traceroute tool is a valuable network diagnostic tool that helps to understand the actual path through which the data is passed from source to destination. Some of the reasons to use the Traceroute tool are stated below.
- Identify Network Hops: Traceroute reveals the path that packets take from the source to the destination. It displays the IP addresses of each router or hop along the route.
- Diagnose Latency Issues: By showing the round-trip time for each hop, traceroute helps identify where latency or delays occur. This information is crucial for diagnosing slow network connections.
- Detect Packet Loss: Traceroute can identify routers or links where packet loss is occurring. This is important for understanding and resolving issues that may impact the reliability of a network connection.
- Verify Routing Paths: It allows you to verify whether the packets are taking the expected path to the destination. Unexpected routes could indicate routing misconfigurations or network issues.
Working of Traceroute Tool
The working Traceroute Tool can be broken down into 7 different steps which are listed and described below:
- Initialization: Traceroute begins by sending a packet to the destination with a Time-to-Live (TTL) set to 1.
- Packet Transmission: The packet is sent to the destination. The first router encountered decrements the bto 0, discards the packet, and sends an ICMP Time Exceeded message back to the source.
- First Set of Results: The source records the round-trip time for the first hop and the IP address of the first router. Another packet is sent with a TTL of 2.
- Iterative Process: Steps 2 and 3 are repeated, increasing the TTL with each iteration. This reveals successive routers along the network path.
- Destination Reached: When a packet reaches the destination, the destination sends an ICMP Echo Reply back to the source.
- Recording Information: Round-trip time and IP addresses are recorded for each hop along the route.
- Output Presentation: Traceroute compiles and displays the recorded information, presenting the route to the destination with associated round-trip times.
Prerequisites:
- Linux Environment: This tutorial assumes you are working in a Linux environment. The provided instructions and script are tailored for Linux systems.
- Terminal Access: You should have access to a terminal or command-line interface on your Linux system. Most Linux distributions provide this by default.
- Python Installed: The provided script in the tutorial uses Python. Python is commonly pre-installed on many Linux distributions.
Creating the Python Script
In this section, we will develop the Python Script for Traceroute. We will break down the script into multiple steps to ease the understanding of implementation.
Step 1: Importing Libraries
Firstly, we need to import all the essential libraries required for various functionalities. Below are the libraries that we will be using for Traceroute implementation.
- socket : For DNS resolution.
- struct : For packing and unpacking binary data.
- time : For time-related functions.
- scapy : A Packet manipulation library.
- argparse : For parsing command-line arguments.
Step 2: Developing Traceroute Function
Here, the traceroute function performs the below operations:
- destination_ip = socket.gethostbyname(destination) : Resolves the destination host to its IP address using DNS.
- port = 33434 : This is the default destination port for traceroute. The choice of this port is arbitrary but commonly used.
- The function then enters a loop, incrementing the TTL for each iteration, and sends UDP packets to the destination using Scapy.
- The script interprets the responses and prints information about each hop or timeout.
- The script increments the TTL for each iteration and breaks out of the loop when the destination is reached or the TTL exceeds the specified maximum hops.
Step 3: Main Function with Argument Parsing
In this step, we will develop the main function with the input argument passing to the script.
The main function performs the below operations:
- Argument Parsing : This part utilizes the argparse library to parse command-line arguments. It defines three arguments: destination (the target host or IP address), max-hops (maximum number of hops), and timeout (timeout for each packet).
- Printing Information : The script prints a user-friendly message indicating the destination, maximum hops, and timeout values.
- Calling Traceroute Function : It then calls the traceroute function with the provided arguments.
Step 4: Script Execution
The below code snippet executes the main function when the script is run directly.
Here, we are checking if the script is being run directly (not imported as a module) using if __name__ == "__main__": . If true, it executes the main function, initiating the traceroute.
Steps to create and execute Python Script
Step 1: Open the terminal window using the keyboard shortcut “ Ctrl + Alt + T “.
Step 2: Using any text editor like Vim , vi, or Nano , open a new blank file in the text editor.
Step 3: We need to write the script below in the created file tracerouteTool.py .
Step 4: Install the scapy package by executing the below pip command in the terminal command:
Step 5: Now, execute the created script by running the the command with the command line input.
Explanation:
- In the above command, it executes a Python script named tracerouteTool.py with the argument geeksforgeeks.org and the maximum hops set to 10 (-m 10) .
- The script simulates a traceroute to ' geeksforgeeks.org ', displaying the route with each hop, round-trip time, and corresponding IP address.
- The output displays the network path taken to reach the destination IP address (8.8.8.8) in a maximum of 10 hops.
Frequently Asked Questions (FAQs)
Q1. Why does Traceroute use UDP?
Traceroute uses UDP (User Datagram Protocol) by default because it doesn't establish a connection like TCP. UDP allows the traceroute program to send packets without waiting for acknowledgment, which is essential for the quick and lightweight probing of network hops.
Q2. What is the use of port 33434 in Traceroute?
Port 33434 is the default starting port for the UDP packets in a traceroute. The choice of this port is somewhat arbitrary but commonly used. As the packets traverse the network, the destination port is incremented with each hop, providing a distinctive identifier for each packet.
Q3. Why does Traceroute increment the Time-to-Live (TTL) field?
The Time-to-Live (TTL) field in the IP header is used to limit the lifetime of a packet. In traceroute, the TTL is initially set to 1, and with each hop, it is incremented. Routers along the path decrement the TTL, and when it reaches 0, the router discards the packet and sends an ICMP Time Exceeded message back. This process helps identify each hop in the route.
Q4. How does Traceroute handle firewalls?
Traceroute may encounter firewalls that block ICMP Time Exceeded messages or UDP packets. In such cases, it might not receive the expected responses. Firewalls can affect the accuracy of traceroute results, and some networks intentionally block or limit ICMP traffic for security reasons.
Q5. What are common issues causing incomplete Traceroute results?
Incomplete traceroute results can be caused by various factors, including firewalls, routers that don't decrement TTL, or routers configured not to generate ICMP Time Exceeded messages. Additionally, some networks prioritize certain types of traffic, affecting the responsiveness of traceroute probes.
In conclusion, the provided Python script offers a custom implementation of the traceroute functionality. It consists of raw sockets and ICMP/UDP protocols to simulate the traceroute process, showcasing the network path to a specified destination, ' geeksforgeeks.org ' in the above example. The script displays standard traceroute output format, presenting a detailed view of each hop, round-trip times, and corresponding IP addresses along the route. By combining Python's socket and struct modules, the script provides a practical and informative tool for network diagnostics and analysis, contributing to the understanding of data packet traversal through different routers in a network.
Similar Reads
- Traceroute Implementation on Python In Network information discovery, the traceroute tool is a fundamental utility in a Linux environment. Although the tool is already developed for the command line utility, we can still make our own Traceroute tool using Python language. We will explore the fundamentals of ICMP (Internet Control Mess 9 min read
- How to Read a Traceroute? Traceroute is a network diagnostic tool used to track the path that data packets take from one computer to another across a network (like the internet). It helps in determining the route and measuring the transit delays of packets over the internet. It's especially useful for identifying network iss 8 min read
- Implementation of Worst fit memory management in Python Worst Fit memory management is a memory allocation algorithm where the largest available block of memory is allocated to a process requesting memory. It aims to maximize the utilization of memory by allocating the largest available block to a process. Examples: Let's consider an example with memory 2 min read
- Getting Started with Python Programming To get started with Python, let's first finish the installation steps. Here's a basic guide to setup Python in your system. Install PythonBefore starting this Python course first, you need to install Python on your computer. To install Python on your computer, follow these steps: Download Python: Go 2 min read
- Traceback in Python Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter. Useful when you want to print the stack trace at any step. They are usually seen when 8 min read
- One-Dimensional Tensor in Pytorch In this article, we are going to discuss a one-dimensional tensor in Python. We will look into the following concepts: Creation of One-Dimensional TensorsAccessing Elements of TensorSize of TensorData Types of Elements of TensorsView of TensorFloating Point TensorIntroduction The Pytorch is used to 5 min read
- Python seek() function The concept of file handling is used to preserve the data or information generated after running the program. Like other programming languages like C, C++, Java, Python also support file handling. Refer the below article to understand the basics of File Handling. File Handling in Python. Reading and 2 min read
- Introduction to PyVista in Python Pyvista is an open-source library provided by Python programming language. It is used for 3D plotting and mesh analysis. It also provides high-level API to simplify the process of visualizing and analyzing 3D data and helps scientists and other working professionals in their field to visualize the d 4 min read
- How to do Mathematical Modeling in Python? Mathematical modeling is a powerful tool used in data science to represent real-world systems and phenomena through mathematical equations and algorithms. Python, with its rich ecosystem of libraries, provides an excellent platform for developing and implementing mathematical models. This article wi 8 min read
- Python Print Exception An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. In this article, we are goin 5 min read
- Python PyTorch – torch.linalg.solve() Function In this article, we will discuss torch.linalg.solve() method in PyTorch. Example: Let's consider the linear equations : 6x + 3y = 1 3x - 4y = 2 Then M values can be - [[6,3],[3,-4]] and t is [1,2]torch.linalg.solve() Function The torch.linalg.solve() method is used to solve a square system of linear 4 min read
- Creating Your Own Python IDE in Python In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and goin 3 min read
- How to Install Python-PyMedia on Linux? Are you having doubts about Installing Python-PyMedia on your Linux System? If so, your search for the best installation guide ends here. This article covers all the insights about Python-PyMedia, its features, and installation. As you finish this article, you will have all the information required 6 min read
- Releasing Memory in Python Python's memory management is primarily handled by its built-in garbage collector (GC), which automatically deallocates memory that is no longer in use. However, to optimize memory usage, developers can employ explicit techniques to manage memory more effectively, especially in long-running or memor 4 min read
- How to get value from address in Python ? In this article, we will discuss how to get the value from the address in Python. First, we have to calculate the memory address of the variable or python object which can be done by using the id() function. Syntax: id(python_object) where, python_object is any python variable or data structure like 4 min read
- Implementation of First Fit Memory Management in Python First Fit memory management is a technique used in operating systems for allocating memory to processes. When a process requests memory, the allocator searches the available memory blocks from the beginning of the memory and allocates the first block that is large enough to accommodate the process. 2 min read
- How to pass an array to a function in Python In this article, we will discuss how an array or list can be passed to a function as a parameter in Python. Pass an array to a function in Python So for instance, if we have thousands of values stored in an array and we want to perform the manipulation of those values in a specific function, that is 4 min read
- Traceroute Command in Linux with Examples In networking, understanding the path that data packets take from one point to another is crucial for diagnosing and troubleshooting connectivity issues. One of the most valuable tools for this purpose is the traceroute command in Linux. Traceroute is a command-line tool used in Linux or other opera 8 min read
- How to Install Python-logging module on Linux? A programmer's backpack should include a logging library. It can aid in the development of a better knowledge of a program's flow and the discovery of scenarios that you may not have considered when designing. Because most third-party Python libraries employ logging, you may combine your log message 2 min read
- Geeks Premier League
- Geeks Premier League 2023
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
Navigation Menu
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications You must be signed in to change notification settings
Python Programming: Traceroute (CS-GY 6843)
eltahsow/traceroute-1
Folders and files, repository files navigation.
Computer Networking – Assignment 5
Lab 5: ICMP Traceroute Lab In this lab you will learn how to implement a traceroute application using ICMP request and reply messages. The checksum and header making are not covered in this lab, refer to the ICMP ping lab for that purpose, the naming of most of the variables and socket is also the same.
Traceroute is a computer networking diagnostic tool which allows a user to trace the route from a host running the traceroute program to any other host in the world. Traceroute is implemented with ICMP messages. It works by sending ICMP echo (ICMP type ‘8’) messages to the same destination with increasing value of the time-to-live (TTL) field. The routers along the traceroute path return ICMP Time Exceeded (ICMP type ‘11’) when the TTL field becomes zero. The final destination sends an ICMP reply (ICMP type ’0’) messages on receiving the ICMP echo request. The IP addresses of the routers which send replies can be extracted from the received packets. The round-trip time between the sending host and a router is determined by setting a timer at the sending host.
Your task is to develop your own Traceroute application in python using ICMP. Your application will use ICMP but, in order to keep it simple, will not exactly follow the official specification in RFC 1739.
Code Below you will find the skeleton code for the client. You are to complete the skeleton code. The places where you need to fill in code are marked with #Fill in start and #Fill in end. Each place may require one or more lines of code.
Additional Notes
- You do not need to be concerned about the checksum, as it is already given in the assignment skeleton code.
- This lab requires the use of raw sockets. In some operating systems (e.g. MacOS, Windows), you may need administrator/root privileges to be able to run your Traceroute program.
- Local testing may require you to turn your firewall or antivirus software off to allow the messages to be sent and received. However, Gradescope is not impacted by this.
- See the end of Lab 4 ‘ICMP Pinger’ programming exercise for more information on ICMP.
What to Hand in Use your GitHub repository to upload the complete code for the assignment. The name of the file you submit should be “solution.py”.
Testing the Pinger Test your client by running your code to trace google.com or bing.com. Your output should return a list and meet the acceptance criteria format provided below.
Output Requirements (Acceptance Criteria) Your code must produce the traceroute output in the format provided below for Gradescope to verify your code is working correctly.
Your trace must collect hop number, roundtrip time (rtt), host ip, and the hostname. If a hostname is not available for a host, you should provide an explicit hostname as “hostname not returnable”. Also, if a host is timing out (not responding), you must record this in your trace list item with the text “Request timed out”. Example provided below:
Example: 1 12ms 10.10.111.10 hop1.com 2 30ms 10.10.112.10 hostname not returnable 3 * Request timed out 4 5ms 10.10.110.1 target-host.com
Your get_route() function must return a nested list with trace output. That is, each trace row must be a list that includes the trace results as individual items in the list, which is also inside an overall traceroute list. Example provided below:
Example: [ [‘1’, ‘12ms’, ‘10.10.111.10’, ‘hop1.com’], [‘2’, ‘30ms’, ‘10.10.112.10’, ‘hostname not returnable’], [‘3’, ‘*’, ‘Request timed out’], [‘4’, ‘5ms’, ‘10.10.110.1’, ‘target-host.com’] ]
Note: Your output will be parsed to verify that it includes the relevant information, so if you do not provide the output of your function in a nested list, your solution will not work correctly and you will not receive points. Also, note that the example lists include all data as strings.
Skeleton Code Code is available below and on Google Drive: https://docs.google.com/document/d/17WddCRB1KFY6FwzGEW4oGaG67QjYwtDNhZGWMN3Ik4M/edit?usp=sharing
from socket import * import os import sys import struct import time import select import binascii
ICMP_ECHO_REQUEST = 8 MAX_HOPS = 30 TIMEOUT = 2.0 TRIES = 1
The packet that we shall send to each router along the path is the ICMP echo
Request packet, which is exactly what we had used in the icmp ping exercise., we shall use the same packet that we built in the ping exercise.
def checksum(string): csum = 0 countTo = (len(string) // 2) * 2 count = 0
def build_packet(): #Fill in start # In the sendOnePing() method of the ICMP Ping exercise ,firstly the header of our # packet to be sent was made, secondly the checksum was appended to the header and # then finally the complete packet was sent to the destination.
def get_route(hostname): timeLeft = TIMEOUT tracelist1 = [] #This is your list to use when iterating through each trace tracelist2 = [] #This is your list to contain all traces
@Edited by Chris Avalos 9.27.2020
FAQ Q: I am getting the following error in gradescope: “cp: cannot stat '/autograder/submission/solution.py': No such file or directory” A: If you are submitting a python solution, all python submissions must have the filename titled “solution.py” (minus the quotation marks). Make sure your file meets this naming requirement.
Recommended Textbook Reference Chapter 5: 5.6 ICMP: The Internet Control Message Protocol
Most Common issues Not returning anything from your function Not returning data in the correct format as laid out in the acceptance criteria example Recommend to print out your returned values and compare them to the acceptance criteria example formatting
- Python 100.0%
关键词 > Python代写
Python Programming Assignment 4: Traceroute
发布时间: 2023-07-10
Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit
Python Programming Assignment 4: Tra ceroute
In this assignment you will continue to build your understanding of IP, ICMP, and Traceroute using Python socket programming. Although published before the ICMP Pinger Python lab is due, I would highly recommend finishing that assignment before beginning this one as some of the core components and learnings are borrowed from there – e.g. the checksum and header creation is not provided, but can be referenced from the ICMP pinger.
Traceroute is a computer networking diagnostic tool which allows a user to trace the route from a host running the traceroute program to any other host in the world. Traceroute is implemented with ICMP messages. It works by sending ICMP echo (ICMP type ‘8’) messages to the same destination with increasing value of the time-to-live (TTL) field. The routers along the traceroute path return ICMP Time Exceeded (ICMP type ‘11’ ) when the TTL field become zero. The final destination sends an ICMP reply (ICMP type ’0’ ) messages on receiving the ICMP echo request. The IP addresses of the routers which send replies can be extracted from the received packets. The round-trip time between the sending host and a router is determined by setting a timer at the sending host.
Your task is to develop your own Traceroute application in python using ICMP. Your application will use ICMP but, in order to keep it simple, will not exactly follow the official specification in
RFC 1739
Skeleton code has been provided below. Your job is to fill in the code blocks between #Code Start and #Code End. Between each start and end, it may require one or more lines of code to complete this piece.
Additional Notes
1. The checksum from ICMP pinger can be used in this lab
2. For raw socket programming you will likely need root access. If you face issues, try running with sudo
3. Not all websites accept ICMP traffic, so try with different hosts
4. Don ’ t be afraid to reference back to the ICMP pinger lab!
What to submit
Run your code against 3 different hosts, at least 1 of which is in another country. Submit your code and screenshots of the output from each of the 3 runs.
from socket import *
import os
import sys
import struct
import time
import select
import binascii
ICMP_ECHO_REQUEST = 8
TIMEOUT = 2.0
TRIES = 2
# The packet that we shall send to each router along the path is the
ICMP echo
# request packet, which is exactly what we had used in the ICMP ping
# We shall use the same packet that we built in the Ping exercise
def checksum (str):
#Code Start
#Code End
def build_packet ():
# In the sendOnePing () method of the ICMP Ping exercise
,firstly the header of our
# packet to be sent was made, secondly the checksum was
appended to the header and
# then finally the complete packet was sent to the destination.
# Make the header in a similar way to the ping exercise.
# Append checksum to the header.
# Don ’ t send the packet yet , just return the final packet in
this function.
# So the function ending should look like this
#packet = header + data
#return packet
def get_route (hostname):
timeLeft = TIMEOUT
for ttl in xrange (1,MAX_HOPS):
for tries in xrange (TRIES):
destAddr = gethostbyname (hostname)
# Make a raw socket named mySocket
mySocket.setsockopt (IPPROTO_IP, IP_TTL, struct.pack ( 'I ',
mySocket.settimeout (TIMEOUT)
d = build_packet ()
mySocket.sendto (d, (hostname, 0))
t= time.time ()
startedSelect = time.time ()
whatReady = select.select ( [mySocket], [], [],
howLongInSelect = (time.time () - startedSelect)
if whatReady [0] == []: # Timeout
print " * * * Request timed
recvPacket, addr = mySocket.recvfrom (1024)
timeReceived = time.time ()
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
except timeout:
# Fetch the icmp type from the IP packet
if type == 11:
bytes = struct.calcsize ("d")
timeSent = struct.unpack ("d", recvPacket [28:28 +
bytes]) [0]
print " %d rtt=%.0f ms %s" % (ttl,
(timeReceived -t)*1000, addr [0])
elif type == 3:
elif request_type == 0:
print " %d rtt=%.0f ms %s" % (ttl, (timeReceived
-timeSent)*1000, addr [0])
print "error"
mySocket.close ()
get_route ("google.com")
CS代写专家 Essay代写 51作业君 java代写
daixieit
地址:广州大道中 Clifford Street,Berkeley,California
早上8:00-凌晨3:00(中国时间)
7:00PM—3—2:00PM(北美时间)
Project 2 - Traceroute
Table of contents, project objectives, description, getting started, deliverables, sample output.
In this course project, you will develop a Python script that probes the route from the local machine to a given host address.
The traceroute program identifies the IP addresses of all intermediary machines in between the source and destination. A UDP-based traceroute program is discussed in the class. In this project, you will implement such a tool with the following features.
- The tool must be implemented in python3 and utilize scapy for custom packet generation. Aside from the socket library, no additional libraries are allowed to be used.
- The first line of the .py script must be the location of the Python3 interpreter: #!/bin/env python3
- Input argument : The tool should accept a single argument - the hostname or IP address of the destination host.
- Max hops : Your tool must be able to identify all IP addresses in the path with the distance less that or equal to 20 hops. (In contrast, the default limit for traceroute in Linux is 30 hops.)
- Max probes : Your tool must attempt for only one probe for a node at a certain distance. (In contrast, the traceroute tool in Linux sends three probes for a specific distance by default.)
- This is different from traceroute in Linux, which begins all traceroutes with destination port number 33434 and increments by 1 for each probe. That is, the first probe has destination port number 33434, the second probe has destination port number 33435, etc.
- Source port number : Your tool should pick a random high number for the source UDP port for each probe. (The port fields are two bytes each in size, so don't pick a random number higher than 2 16 or 65535!)
- The Linux-based tool reports the host name in addition to the discovered IP address whenever possible. This is out of scope of this project.
- Your tool must stop sending probes as soon as it receives an ICMP Port Unreachable message from the target.
- It is desirable to eliminate verbosity of Scapy within the tool. You may use conf.verb = 0 for this purpose.
- It is desirable to report the discovered IP addresses along the path to the target in real-time fashion (similar to Linux-based tool), rather than computing a whole list of addresses up to the target and reporting them in a single burst.
- At the top of the script file, briefly describe how your tool works.
As a rule of thumb, if your traceroute program output differs from the Linux-based tool to a great extent, then you are probably doing something wrong. Compare the traffic generated by your tool versus the traffic from the Linux-based tool. That may help you to tune your probing packets appropriately.
First, ensure traceroute is installed in your Linux VM:
Then, start Wireshark, capture a traceroute sequence to 8.8.8.8 (Google public DNS, a good example target), and stop capture.
Model your code against the traceroute behavior you see in Wireshark and follow the project requirements above.
Note that your traceroute from the standard Linux utility should look something like this. If you don't see network hops, and instead see line after line of * * * , then you have a networking problem in your VM that should be solved before writing your Python code. (Switching from NAT to Bridged mode in your virtual machine may help).
- Scapy Documentation
- The Packet Geek: Building Network Tools with Scapy
- How to do a reverse DNS lookup in Python
Submit a single Python script that implements traceroute to the Canvas CMS Project 2 assignment.
If using PyCharm, do not submit your venv environment. Before submitting, test to ensure you can run your program outside of PyCharm on the command line.
Running the tool may generate an output similar to the following in a terminal in Ubuntu Linux.
Implementing a simple traceroute clone in Python
I was watching this amazing lightning talk 1 by Karla Burnett and wanted to understand how traceroute works in Unix. Traceroute is a tool that shows the route of a network packet from your computer to another computer on the internet. It also tells you how long it takes for the packet to reach each stop along the way.
It’s useful when you want to know more about how your computer connects to other computers on the internet. For example, if you want to visit a website, your computer sends a request to the website’s server, which is another computer that hosts the website. But the request doesn’t go directly from your computer to the server. It has to pass through several other devices, such as routers, that help direct the traffic on the internet. These devices are called hops. Traceroute shows you the list of hops that your request goes through, and how long it takes for each hop to respond. This can help you troubleshoot network problems, such as slow connections or unreachable websites.
This is how you usually use traceroute :
This returns:
This traceroute output draws the path of a network packet from my computer to example.com ’s server, which has an IP address of 93.184.216.34 . It shows that the packet goes through 11 hops before reaching the destination. The first hop is my router ( 192.168.1.1 ), the second hop is my ISP’s router ( 142.254.158.201 ), and so on. The last column shows the time it takes for each hop to respond in milliseconds (ms). The lower the time, the faster the connection.
Some hops have multiple lines with different names or IP addresses. This means that there are multiple routers at that hop that can handle the traffic, and traceroute randomly picks one of them for each packet. For example, hop 7 has three routers with names starting with lag-11 , lag-21 , and lag-31 . These are probably load-balancing routers that distribute the traffic among them.
The last hop ( 93.184.216.34 ) appears twice in the output. This is because traceroute sends three packets to each hop by default, and sometimes the last hop responds to all three packets instead of discarding them. This is not a problem and does not affect the accuracy of the traceroute.
This is all good and dandy but I wanted to understand how traceroute can find out what route a packet takes and how long it takes between each hop. So I started reading blogs like this 2 one that does an awesome job at explaining what’s going on behind the scene. The gist of it goes as follows.
How traceroute works #
Traceroute works by sending a series of ICMP (Internet Control Message Protocol) echo request packets, which are also known as pings, to the target IP address or URL that you want to reach. Each packet has an associated time-to-live (TTL) value, which is a number that indicates how many hops (or intermediate devices) the packet can pass through before it expires and is discarded by a router. Yeah, strangely, TTL doesn’t denote any time duration here.
Traceroute starts by sending a packet with a low TTL value, usually 1. This means that the packet can only make one hop before it expires. When a router receives this packet, it decreases its TTL value by 1 and checks if it is 0. If it is 0, the router discards the packet and sends back an ICMP time exceeded message to the source of the packet. This message contains the IP address of the router that discarded the packet. This is how the sender knows the IP address of the first hop (router, computer, or whatsoever).
Traceroute records the IP address and round-trip time (RTT) of each ICMP time exceeded message it receives. The RTT is the time it takes for a packet to travel from the source to the destination and back. It reflects the latency (or delay) between each hop.
Traceroute then increases the TTL value by 1 and sends another packet. This packet can make 2 hops before it expires. The process repeats until traceroute reaches the destination or a maximum TTL value, usually 30. When the returned IP is the same as the initial destination IP, traceroute knows that the packet has completed the whole journey. By doing this, traceroute can trace the route that your packets take to reach the target IP address or URL and measure the latency between each hop. The tool prints out the associated IPs and latencies as it jumps through different hops.
I snagged this photo from an SFU (Simon Fraser University) slide 3 that I think explains the machinery of traceroute quite well:
Writing a crappier version of traceroute in Python #
After getting a rough idea of what’s going on underneath, I wanted to write a simpler and crappier version of traceroute in Python. This version would roughly perform the following steps:
- Establish a UDP socket connection that’d be used to send empty packets to the hops.
- Create an ICMP socket that’d receive ICMP time exceeded messages.
- Start a loop and use the UDP socket to send an empty byte with a TTL of 1 to the first hop.
- The TTL value of the packet would be decremented by 1 at the first hop. Once the TTL reaches 0, the packet would be discarded, and an ICMP time exceeded message would be returned to the sender through the ICMP socket. The sender would also receive the address of the first hop.
- Calculate the time delta between sending a packet and receiving the ICMP time exceeded message. Also, capture the address of the first hop and log the time delta and address to the console.
- In the subsequent iterations, the TTL value will be incremented by 1 (2, 3, 4, …) and the steps from 1 through 5 will be repeated until it reaches the max_hops value, which is set at 64.
Here’s the complete self-contained implementation. I tested it on Python 3.11:
Running the script will give you the following nicely formatted output:
Storytelling with traceroute ↩︎
How traceroute works ↩︎
Traceroute machinery slide ↩︎
Recent posts
- Function types and single-method interfaces in Go
- Injecting Pytest fixtures without cluttering test signatures
- Explicit method overriding with @typing.override
- Quicker startup with module-level __getattr__
- Docker mount revisited
- Topological sort
- Writing a circuit breaker in Go
- Discovering direnv
- Notes on building event-driven systems
Marin Atanasov Nikolov
A place about Open Source Software, Operating Systems and some random thoughts
A simple traceroute(8) implementation in Python
traceroute(8) is one of these tools that sysadmins often use when a networking issue arises and needs troubleshooting.
The traceroute(8) tool is used to trace the route packets take in a network to a destination host. The tool is used to diagnose possible problems in the network and also measure the latency between systems.
The way that traceroute(8) works is by sending a sequence of UDP ICMP Echo Request packets to a destination host with a specified Time-To-Live (TTL) value.
Each time a packet reaches a gateway, the gateway checks if the TTL of a packet is greater than one, reduces the TTL of the packet by one and transmits the packet to its next hop. If the TTL of a packet is one, then the gateway discards the packet and sends back a Time exceeded response to the source client informing it that the destination host could not be reached as the packet TTL has exceeded.
These Time exceeded responses are then being used by the source client to determine the intermediate gateways sitting between the source and destination system by manipulating the TTL of packets on each iteration until we finally reach our destination host or the max number of iterations (hops limit) has been reached.
You can read more about traceroute(8) at the Traceroute page on Wikipedia .
Below you can find a Python module that creates a very basic implementation of traceroute(8) .
Please also note, that the receiver socket used in the class below is a raw socket ( socket.SOCK_RAW ), so you will need root privileges when binding it.
You can also find the code below in the pytraceroute repository on Github.
IMAGES
COMMENTS
Sep 5, 2024 · Python Installed: The provided script in the tutorial uses Python. Python is commonly pre-installed on many Linux distributions. Creating the Python Script. In this section, we will develop the Python Script for Traceroute. We will break down the script into multiple steps to ease the understanding of implementation. Step 1: Importing Libraries ...
These programs, titled "Traceroute" (traceroute.py) and "Ping" (ping.py), are python projects developed by Josh Embury for CS372 Section 400 at Oregon State University. The code provided in the IcmpHelperLibrary.py file includes implementation of the traceroute and ping programs, similar to the programs found on Linux operating systems.
Attribution: this assignment is based on ICMP Pinger Lab and ICMP Traceroute Lab from Computer Networking: a Top-Down Approach by Jim Kurose and Keith Ross. It was modified for use in CSC249: Networks at Smith College by R. Jordan Crouser in Fall 2022, and further modified by B. Cheikes for use in ...
Python Programming_ICMP & Traceroute. New York University. CS-GY 6903. lab. ... View Computer Networking Assignment 4.docx from CS-GY 6903 at New York University. Comp...
Traceroute is a computer networking diagnostic tool which allows a user to trace the route from a host running the traceroute program to any other host in the world. Traceroute is implemented with ICMP messages. It works by sending ICMP echo (ICMP type ‘8’) messages to the same destination with increasing value of the time-to-live (TTL) field.
Jul 10, 2023 · Python Programming Assignment 4: Tra ceroute. In this assignment you will continue to build your understanding of IP, ICMP, and Traceroute using Python socket programming. Although published before the ICMP Pinger Python lab is due, I would highly recommend finishing that assignment before beginning this one as some of the core components and learnings are borrowed from there – e.g. the ...
Jul 20, 2009 · Just include the URL you want to traceroute to: import webb webb.traceroute("your-web-page-url") If you wish to store the traceroute log to a text file automatically, use the following command: webb.traceroute("your-web-page-url",'file-name.txt') Similarly a IP address of a URl (server) can be obtained with the following lines of code:
In this course project, you will develop a Python script that probes the route from the local machine to a given host address. Description. The traceroute program identifies the IP addresses of all intermediary machines in between the source and destination. A UDP-based traceroute program is discussed in the class.
Jun 1, 2023 · Traceroute then increases the TTL value by 1 and sends another packet. This packet can make 2 hops before it expires. The process repeats until traceroute reaches the destination or a maximum TTL value, usually 30. When the returned IP is the same as the initial destination IP, traceroute knows that the packet has completed the whole journey ...
Jun 24, 2015 · traceroute(8) is one of these tools that sysadmins often use when a networking issue arises and needs troubleshooting. The traceroute(8) tool is used to trace the route packets take in a network to a destination host. The tool is used to diagnose possible problems in the network and also measure the latency between systems.