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

  • Notes on building event-driven systems
  • Bash namerefs for dynamic variable referencing
  • Behind the blog
  • Shell redirection syntax soup
  • Shades of testing HTTP requests in Python
  • Taming parametrize with pytest.param
  • HTTP requests via /dev/tcp
  • Log context propagation in Python ASGI apps
  • Please don't hijack my Python root logger
  • The *nix install command

python programming assignment 4 traceroute

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.

DZone

  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
  • Manage My Drafts

Celebrate a decade of Kubernetes. Explore why K8s continues to be one of the most prolific open-source systems in the SDLC.

What's in your tech stack? Tell us about it in our annual Community Survey, and help shape the future of DZone!

Learn how to build your data architecture with open-source tools + design patterns for scalability, disaster recovery, monitoring, and more.

Cloud + data orchestration: Demolish your data silos. Enable complex analytics. Eliminate I/O bottlenecks. Learn the essentials (and more)!

  • Instant Integrations With API and Logic Automation
  • How to Move System Databases to Different Locations in SQL Server on Linux
  • Simplifying Access to Db2 Databases in Jupyter Notebook
  • Using Docker for Python Flask Development
  • Practical Generators in Go 1.23 for Database Pagination
  • Algorithmic Advances in AI-Driven Search: Optimizing Query Processing for Precision and Speed
  • Documenting a Java WebSocket API Using Smart-Doc
  • Founder Mode?
  • Data Engineering

Traceroute Command in Python and How to Read a Traceroute

Traceroute or tracert command traces the hops between the origin and destination. in this post, we'll learn traceroute and how it helps in network troubleshooting..

camimi Morales user avatar

Join the DZone community and get the full member experience.

On operating systems like Windows or Linux, there is an invaluable tool called the traceroute command (on Windows, the equivalent command is called tracert ). This command-line tool enables system administrators or network engineers to troubleshoot common networking issues.

Administrators use a traceroute to probe for bottlenecks whenever a user complains that the connection to a website or server is slow. In addition, the traceroute command is used if a server is unreachable, as it will show which particular part of the network route is problematic.

How Does Traceroute Work?

The traceroute command works by sending out network packets to a destination host. Each host also will show their response times.

By analyzing the route, network engineers can determine if the routing is optimal. The response time provides vital clues to pinpoint which hops have latency issues.

To get the usual traceroute result along with geolocation results such as country, region, cities, and much more, the system administrator can use the Python IP2Trace tool. Below is a simple demo of the features that IP2Trace brings. 

Installing Python IP2Trace

Let’s get started with the demo. Firstly, you’ll need to install some prerequisites. NOTE: The installation steps below are for the Debian 11 Linux operating system as that’s our demo machine.

Secondly, to install Python and the IP2Trace, run the below commands:

After that, download the IP2Location BIN database files. You can get the IP2Location LITE database and download it for free.

After downloading the zipped file containing the BIN, extract the BIN file out and store it in our recommended folder /usr/share/ip2location . Just create the folder if it doesn’t exist.

A Simple Demo of the IP2Trace Usage Using DB25

It is pretty straightforward to use the IP2Trace command. Below we will query the basic geolocation data from our DB25.BIN file (default folder is the recommended folder above) for the IP address 8.8.8.8.

See the result below:

python programming assignment 4 traceroute

* By default, IP2Trace returns the country code, region, and city when data is available.

Each line is a host or hops along the route to the final destination server. Pay close attention to the 3 numbers after the IP address. These are the response time for each of the 3 packets that were sent out.

As we’re using the DB25 database, let’s modify the command above to output more fields from the BIN file. We want to display the country code, country name, region name, city name, ISP name, network speed, and usage type. Analyzing these data helps to provide further insights into the root cause of the issues.

python programming assignment 4 traceroute

Discover what are the various options supported by the command in IP2Location Traceroute Application . You can use the command below too. 

  • IP2Trace improves on the existing traceroute command by adding the geolocation info.
  • Geolocation data can make troubleshooting network issues easier.
  • It is easier to install the Python IP2Trace compared to the C IP2Trace.
  • Require installation of Python to function.
  • Must have experience in running commands in the console.
  • Needs regular updates of the BIN file to maintain the accuracy of geolocation.

Traceroute is a command-line tool commonly used by network and system administrators. For instance, system administrators use a traceroute to monitor internet connectivity. It helps to visualize the path traffic, including packet loss and high latency.

Opinions expressed by DZone contributors are their own.

Partner Resources

  • About DZone
  • Support and feedback
  • Community research
  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone
  • Terms of Service
  • Privacy Policy
  • 3343 Perimeter Hill Drive
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture

Network Troubleshooting Techniques: Ping, Traceroute, PathPing

Network Troubleshooting is a way to maintain your computer network, ensuring optimal performance, and addressing issues that may disrupt connectivity. when any problems arise, network administrators and IT professionals use tools such as Ping, Traceroute, and PathPing to identify and solve a problem.

Ping is a command that sends a small packet of data to any network device and waits for its response. Traceroute traces the route from source to destination and it helps identify any delay or bottleneck. PathPing combines the functionality of both Ping and Traceroute commands to troubleshoot the network. In this article, we will learn about Ping, Traceroute, and PathPing tools, and how to use them to troubleshoot the network.

A Ping stands for Packet Internet Groper. It is a widely used command for identifying connectivity between two network connections. It uses Internet Control Message Protocol (ICMP) to send a request to the target host and wait for a response. It measures the round-trip time for data packets to travel from the source to the destination and back.

ping

ping command

Explanation

It shows that we have sent 4 request (packet) and received acknowledgment of all the requests and there is Zero loss. and It shows a minimum, maximum and average round trip time in milliseconds.

Traceroute is also called as a tracert . It traces the route from source to the destination. It is achieved by using ICMP to send a request. It revels the all routers between source and destination by displaying their IP Address to detect where the packet loss or latency occurs.

tracert

Each lines shows a route with round-trip time. the first line shows a router has 2409:4080:8e1b:cf24::7f IPv6 address and round-trip time is 1ms. and the second line has a timeout. This means that the router at hop 2 did not response to the ICMP request within the time limit.

PathPing command is a combination of ping and tracert command. It sends request to each routers that comes between source and destination and compute result based on response from each router. It provide continues monitoring of the network path which allow network administrator to observe changes in performance.

pathping

It shows Hop 0 is a source with no packet loss, Hop 1 with round-time of 4ms with no packet loss and Hop 2 shows a timeout with * * * indicating that there was no response from this Hop (Router).

Learning of Troubleshooting commands such as Ping , Traceroute , PathPing is necessary for Network Administrator and IT Professional to maintain computer network and solve a problems.

FAQ on Network Troubleshooting Techniques

Q.1: what is network troubleshooting, and why is it important.

It is a way of maintaining a computer network and it ensures smooth operation and minimizing downtime when there is a issue.

Q.2: What is Ping, and how does it work?

Ping command identify connectivity between two network device by sending request using ICMP .

Q.3: How does Traceroute help in network troubleshooting?

Traceroute traces all the routers from source to destination and display their IP Address to detect where the packet loss or latency occurs.

Q.4: What is PathPing, and how does it differ from Ping and Traceroute?

PathPing is a combination of Ping and Traceroute and It provide continuous monitoring for observing changes in network performance.

author

Similar Reads

  • Geeks Premier League
  • Geeks Premier League 2023

Please Login to comment...

  • How to Watch NFL on NFL+ in 2024: A Complete Guide
  • Best Smartwatches in 2024: Top Picks for Every Need
  • Top Budgeting Apps in 2024
  • 10 Best Parental Control App in 2024
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

logo img

50.005 Computer System Engineering Information Systems Technology and Design Singapore University of Technology and Design Natalie Agus (Summer 2024)

Ping and Traceroute

In this lab exercise, you will learn how to use ping and traceroute programs to measure round trip times and find network routes.

Learning Objectives :

  • Explain how ping and traceroute utilities work.
  • Use the ping utility to measure network round trip times.
  • Use the traceroute utility to find network routes .
  • Observe and understand the effects of varying packet sizes on delays experienced.

You will need both ping and traceroute to be installed on your OS. Most Ubuntu or macOS installations should already include ping by default. You can install traceroute by running sudo apt install traceroute from the command line.

RTT Measurement using ping

The ping utility is one of the most widely-used network utilities. It enables you to measure the time that it takes for a packet to travel through the Internet to a remote host and back .

The ping utility works by sending a short message, known as an echo request to a remote host using the Internet Control Message Protocol (ICMP).When a host that supports ICMP receives an echo-request message, it replies by sending an echo-response message back to the originating host.

In this first part of this lab exercise, you will use the ping utility to send echo requests to a number of different hosts. In many of the exercises, you will be referring to hosts using their domain name rather than their IP addresses 1 . For more information about ping, you can look up its manual page by running man ping from the command line.

The following info is relevant for the next few tasks:

  • ping netflix.com is the easiest and simplest way to ping a server. It will continuously send packets and print out the response (if any). You may press ctrl+c to terminate it.
  • -c [no_of_packets] : specify the number of packets that should be sent by ping before terminating (otherwise it will continue forever until SIGINT 2 is sent by ctrl+c ).
  • -s [packet_size] : set packet size. The default is 56.
  • -i [seconds_interval] : interval of ping packets sent to the destination

Round-Trip Time

The ping utility can be used to measure the round-trip time (RTT).

Round-trip time ( RTT ) is the duration, measured in milliseconds, from when a browser sends a request to when it receives a response from a server.

RTT is one of the key performance metric for web applications.

TASK 1: Use ping to send 10 packets (56 bytes each) to each of the following hosts, and there should be an interval of 5 seconds between each packet sent,

  • www.csail.mit.edu
  • www.berkeley.edu
  • www.usyd.edu.au
  • www.kyoto-u.ac.jp

The size of each packet is 56 bytes by default, but you may observe that the actual size of the packet is larger than 56 bytes. You can look up the manual for ping to understand why such a discrepancy exists.

Fill up the table below in edimension to key in your answer.

Website Successfull % Min RTT Ave RTT Max RTT
www.csail.mit.edu        
www.berkeley.edu        
www.usyd.edu.au        
www.kyoto-u.ac.jp        

Also, go to this online ping test site and ping www.csail.mit.edu

Question From whom do you receive replies? You can get the IP address and use the command whois [ip_address]

TASK 2: Repeat the exercise from Task 1 using packet sizes of 512 and 1024 bytes. Record the minimum , average , and maximum round trip times for each of the packet sizes with a table like the previous task, and head to edimension to key in your answer.

Question Why are the minimum round-trip times to the same hosts different when using 56, 512, and 1024–byte packets?

Unanswered pings

TASK 3: Use ping to send 100 packets to the following host: www.wits.ac.za

Each packet should have a size of 56 bytes, and there should be an interval of 5 seconds between each packet sent.

Record the percentage of the packets sent that resulted in a successful response for each host.

Question What are some possible reasons why you may not have received a response? (Be sure to check the host in a web browser ).

The traceroute utility is another useful network utility. It enables you to trace the route taken by a packet from your machine to a remote host.

Note that if traceroute doesn’t work on your VM, you may:

  • Add the -I option: traceroute -I [ip]
  • Or, use results from tracert (assuming Windows is your host OS).

Here is an example of the output produced when traceroute is used to trace the route taken by a packet to www.mit.edu:

python programming assignment 4 traceroute

The first line of the traceroute output describes what the command is set for. It lists the destination system (e9566.dscb.akamaiedge.net), destination IP address (184.50.104.236), and the maximum number of hops that will be used in the traceroute (64).

The remainder of the output shows information on each hop , where each line is a reply from (typically) a router, in the path between the sender and the final destination .

It is important to note that the number of hops is not an important factor that affects latency.

Each of these lines begins with a host (e.g router) IP on the route from your computer to www.mit.edu, followed by the round-trip time ( RTT ) for 3 packets sent to that host.

For more information about traceroute , you can look up its manual page by running man traceroute from the command line.

TASK 4: Find out how traceroute works. You will need this to answer several questions on eDimension.

Hint traceroute sends a UDP packet to the destination host’s (highly likely) unusable port, with increasing TTL. The routers that reduces the TTL to 0 will send an ICMP TTL Exceeded reply. The end host will send an ICMP Port unreachable reply.

Route Asymmetries

The route taken to send a packet from your machine to the remote host machine is not always the same with the route taken to send a packet from the remote machine back to you.

In this exercise, you will run traceroute in two opposite directions. First, you will run traceroute on a remote host to see the route taken to your network . Then, you will also run traceroute from your computer to see the route taken to that host.

TASK 5: Find out your computer’s public IP address. (Hint: You can use a website like this , or search for “what is my ip” using Google’s search engine.)

TASK 6: Visit this link using your web browser.

Then do the following:

  • Enter your computer’s public IP address as shown in the site
  • Enter the captcha code, then press enter to start a traceroute to your computer’s public IP
  • Take a screenshot of the output

If the output shows that the packet does not reach your IP (request timed out), think about a reason or two on why this is so.

The school might block the website. You can utilise your phone hotspot instead. You’re free to use other similar sites that performs traceroute from their server to your computer’s public IP address. If you have two devices with different IPs (e.g: one uses VPN), then you can also traceroute each other’s IP addresses.

TASK 7: After traceroute finishes running, you should be able to view the route taken from specified locations to your network.

Record the IP address of the first visible hop which will be used in the next step.

In the screenshot below, that will be 213.239.245.241 for example.

python programming assignment 4 traceroute

You can check who that remote host is using the command whois [ip address] , for instance, 213.239.245.241 is indeed described as being in Germany (DE).

python programming assignment 4 traceroute

TASK 8: On your computer, run traceroute using the IP address recorded in the previous step as the remote destination.

python programming assignment 4 traceroute

Question Are the same routers traversed in both directions? If no, could you think of a reason why?

In this lab, we have explored two network utilities: ping and traceroute. This shall help you explain the effects of varying packet sizes on delays experienced.

A domain name is an easy-to-remember alias used to access websites. For example, we access netflix by typing netflix.com and not the actual netflix server’s public IP address. For more information, see here .  ↩

In POSIX-compliant OS, the default action for SIGINT , SIGTERM , SIGQUIT , and SIGKILL is to terminate the process. However, SIGTERM , SIGQUIT , and SIGKILL are defined as signals to terminate the process, but SIGINT is defined as an interruption requested by the user .  ↩

Instantly share code, notes, and snippets.

@abcdabcd987

abcdabcd987 / ICMPPinger.py

  • Download ZIP
  • Star ( 4 ) 4 You must be signed in to star a gist
  • Fork ( 2 ) 2 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save abcdabcd987/eaf210249fab605a75bac3409b614372 to your computer and use it in GitHub Desktop.
import os
import sys
import struct
import time
import select
import socket
import binascii
ICMP_ECHO_REQUEST = 8
def checksum(str):
csum = 0
countTo = (len(str) / 2) * 2
count = 0
while count < countTo:
thisVal = ord(str[count+1]) * 256 + ord(str[count])
csum = csum + thisVal
csum = csum & 0xffffffffL
count = count + 2
if countTo < len(str):
csum = csum + ord(str[len(str) - 1])
csum = csum & 0xffffffffL
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receiveOnePing(mySocket, ID, timeout, destAddr):
global rtt_min, rtt_max, rtt_sum, rtt_cnt
timeLeft = timeout
while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return "Request timed out."
timeReceived = time.time()
recPacket, addr = mySocket.recvfrom(1024)
#Fill in start
#Fetch the ICMP header from the IP packet
type, code, checksum, id, seq = struct.unpack('bbHHh', recPacket[20:28])
if type != 0:
return 'expected type=0, but got {}'.format(type)
if code != 0:
return 'expected code=0, but got {}'.format(code)
if ID != id:
return 'expected id={}, but got {}'.format(ID, id)
send_time, = struct.unpack('d', recPacket[28:])
rtt = (timeReceived - send_time) * 1000
rtt_cnt += 1
rtt_sum += rtt
rtt_min = min(rtt_min, rtt)
rtt_max = max(rtt_max, rtt)
ip_header = struct.unpack('!BBHHHBBH4s4s' , recPacket[:20])
ttl = ip_header[5]
saddr = socket.inet_ntoa(ip_header[8])
length = len(recPacket) - 20
return '{} bytes from {}: icmp_seq={} ttl={} time={:.3f} ms'.format(length, saddr, seq, ttl, rtt)
#Fill in end
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "Request timed out."
def sendOnePing(mySocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy header with a 0 checksum.
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
#Convert 16-bit integers from host to network byte order.
else:
myChecksum = socket.htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1)) # AF_INET address must be tuple, not str
#Both LISTS and TUPLES consist of a number of objects
#which can be referenced by their position number within the object
def doOnePing(destAddr, timeout):
icmp = socket.getprotobyname("icmp")
#SOCK_RAW is a powerful socket type. For more details see: http://sock-raw.org/papers/sock_raw
#Fill in start
#Create Socket here
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
#Fill in end
myID = os.getpid() & 0xFFFF #Return the current process i
sendOnePing(mySocket, destAddr, myID)
delay = receiveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay
def ping(host, timeout=1):
global rtt_min, rtt_max, rtt_sum, rtt_cnt
rtt_min = float('+inf')
rtt_max = float('-inf')
rtt_sum = 0
rtt_cnt = 0
cnt = 0
#timeout=1 means: If one second goes by without a reply from the server,
#the client assumes that either the client's ping or the server's pong is lost
dest = socket.gethostbyname(host)
print "Pinging " + dest + " using Python:"
#Send ping requests to a server separated by approximately one second
try:
while True:
cnt += 1
print doOnePing(dest, timeout)
time.sleep(1)
except KeyboardInterrupt:
if cnt != 0:
print '--- {} ping statistics ---'.format(host)
print '{} packets transmitted, {} packets received, {:.1f}% packet loss'.format(cnt, rtt_cnt, 100.0 - rtt_cnt * 100.0 / cnt)
if rtt_cnt != 0:
print 'round-trip min/avg/max {:.3f}/{:.3f}/{:.3f} ms'.format(rtt_min, rtt_sum / rtt_cnt, rtt_max)
ping(sys.argv[1])
  • Python »
  • 3.12.6 Documentation »
  • The Python Standard Library »
  • Debugging and Profiling »
  • trace — Trace or track Python statement execution
  • Theme Auto Light Dark |

trace — Trace or track Python statement execution ¶

Source code: Lib/trace.py

The trace module allows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.

A popular third-party coverage tool that provides HTML output along with advanced features such as branch coverage.

Command-Line Usage ¶

The trace module can be invoked from the command line. It can be as simple as

The above will execute somefile.py and generate annotated listings of all Python modules imported during the execution into the current directory.

Display usage and exit.

Display the version of the module and exit.

Added in version 3.8: Added --module option that allows to run an executable module.

Main options ¶

At least one of the following options must be specified when invoking trace . The --listfuncs option is mutually exclusive with the --trace and --count options. When --listfuncs is provided, neither --count nor --trace are accepted, and vice versa.

Produce a set of annotated listing files upon program completion that shows how many times each statement was executed. See also --coverdir , --file and --no-report below.

Display lines as they are executed.

Display the functions executed by running the program.

Produce an annotated list from an earlier program run that used the --count and --file option. This does not execute any code.

Display the calling relationships exposed by running the program.

Modifiers ¶

Name of a file to accumulate counts over several tracing runs. Should be used with the --count option.

Directory where the report files go. The coverage report for package.module is written to file dir / package / module .cover .

When generating annotated listings, mark lines which were not executed with >>>>>> .

When using --count or --report , write a brief summary to stdout for each file processed.

Do not generate annotated listings. This is useful if you intend to make several runs with --count , and then produce a single set of annotated listings at the end.

Prefix each line with the time since the program started. Only used while tracing.

These options may be repeated multiple times.

Ignore each of the given module names and its submodules (if it is a package). The argument can be a list of names separated by a comma.

Ignore all modules and packages in the named directory and subdirectories. The argument can be a list of directories separated by os.pathsep .

Programmatic Interface ¶

Create an object to trace execution of a single statement or expression. All parameters are optional. count enables counting of line numbers. trace enables line execution tracing. countfuncs enables listing of the functions called during the run. countcallers enables call relationship tracking. ignoremods is a list of modules or packages to ignore. ignoredirs is a list of directories whose modules or packages should be ignored. infile is the name of the file from which to read stored count information. outfile is the name of the file in which to write updated count information. timing enables a timestamp relative to when tracing was started to be displayed.

Execute the command and gather statistics from the execution with the current tracing parameters. cmd must be a string or code object, suitable for passing into exec() .

Execute the command and gather statistics from the execution with the current tracing parameters, in the defined global and local environments. If not defined, globals and locals default to empty dictionaries.

Call func with the given arguments under control of the Trace object with the current tracing parameters.

Return a CoverageResults object that contains the cumulative results of all previous calls to run , runctx and runfunc for the given Trace instance. Does not reset the accumulated trace results.

A container for coverage results, created by Trace.results() . Should not be created directly by the user.

Merge in data from another CoverageResults object.

Write coverage results. Set show_missing to show lines that had no hits. Set summary to include in the output the coverage summary per module. coverdir specifies the directory into which the coverage result files will be output. If None , the results for each source file are placed in its directory.

A simple example demonstrating the use of the programmatic interface:

Table of Contents

  • Main options
  • Programmatic Interface

Previous topic

timeit — Measure execution time of small code snippets

tracemalloc — Trace memory allocations

  • Report a Bug
  • Show Source

Tracert 0.0.1

pip install Tracert Copy PIP instructions

Released: Apr 29, 2023

This package implements a traceroute tool faster than traceroute/tracert executable.

Verified details

Maintainers.

Avatar for MauriceLambert from gravatar.com

Unverified details

Project links.

  • Documentation
  • License: GPL-3.0 License
  • Author: Maurice Lambert
  • Maintainer: Maurice Lambert
  • Tags network, traceroute, tracert, trace, ping, debug
  • Requires: Python >=3.8

Classifiers

  • 5 - Production/Stable
  • Microsoft :: Windows
  • POSIX :: Linux
  • Python :: 3.9
  • System :: Networking

Project description

Tracert logo

Description

This package implements a traceroute tool faster than traceroute/tracert executable but less accurate for response and without hostname resolution.

Requirements

This package require :

  • python3 Standard Library
  • PythonToolsKit

Installation

Command lines.

  • Github Page

Licensed under the GPL, version 3 .

Project details

Release history release notifications | rss feed.

Apr 29, 2023

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages .

Source Distribution

Uploaded Apr 29, 2023 Source

Hashes for Tracert-0.0.1.tar.gz

Hashes for Tracert-0.0.1.tar.gz
Algorithm Hash digest
SHA256
MD5
BLAKE2b-256
  • português (Brasil)

Supported by

python programming assignment 4 traceroute

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

TCP Traceroute in python

I am writing a python script to perform 'TCP Traceroute'. I learned scapy is a useful library to do this but I`m not getting the results I need. Can anyone help me resolve this? I want the python script to generate similar results as command line.

I am using linux, python 2.7 with scapy 2.4. I am not sure why same ip addresses are shown for all the hops.

When I run this code I get following results:

I want to get the same results which I get when I run tcptraceroute from command line: tcptraceroute 172.217.17.46

Result from command line:

Question1: Is scapy traceroute function really does TCP traceroute? Question2: I am new to scapy and traceroute, Is there something obvious I am missing in the code? Is there any other library which I can use if scapy is not suitable? I would really appreciate the help and any pointers.

NOTE: I WANT TO PERFORM TCP TRACE ROUTE FOR BOTH IPV6 AND IPV4.

Hussain ali's user avatar

Is scapy traceroute function really does TCP traceroute? Yes it does do TCP traceroute (among other things). Take a look at Scapy source-code :

@conf.commands.register def traceroute(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4 = None, filter=None, timeout=2, verbose=None, **kargs): """Instant TCP traceroute traceroute(target, [maxttl=30,] [dport=80,] [sport=80,] [verbose=conf.verb]) -> None""" if verbose is None: verbose = conf.verb if filter is None: # we only consider ICMP error packets and TCP packets with at # least the ACK flag set *and* either the SYN or the RST flag # set filter="(icmp and (icmp[0]=3 or icmp[0]=4 or icmp[0]=5 or icmp[0]=11 or icmp[0]=12)) or (tcp and (tcp[13] & 0x16 > 0x10))" if l4 is None: a,b = sr(IP(dst=target, id=RandShort(), ttl=(minttl,maxttl))/TCP(seq=RandInt(),sport=sport, dport=dport), timeout=timeout, filter=filter, verbose=verbose, **kargs) else: # this should always work filter="ip" a,b = sr(IP(dst=target, id=RandShort(), ttl=(minttl,maxttl))/l4, timeout=timeout, filter=filter, verbose=verbose, **kargs) a = TracerouteResult(a.res) if verbose: a.show() return a,b
def traceroute6(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4 = None, timeout=2, verbose=None, **kargs): """ Instant TCP traceroute using IPv6 : traceroute6(target, [maxttl=30], [dport=80], [sport=80]) -> None """ if verbose is None: verbose = conf.verb if l4 is None: a,b = sr(IPv6(dst=target, hlim=(minttl,maxttl))/TCP(seq=RandInt(),sport=sport, dport=dport), timeout=timeout, filter="icmp6 or tcp", verbose=verbose, **kargs) else: a,b = sr(IPv6(dst=target, hlim=(minttl,maxttl))/l4, timeout=timeout, verbose=verbose, **kargs) a = TracerouteResult6(a.res) if verbose: a.display() return a,b

The following example code is for traceroute ipv6. On Windows platforms, Npcap must be installed.

from scapy.all import * waypoint = "2001:301:0:8002:203:47ff:fea5:3085" target = "2001:5f9:4:7:2e0:81ff:fe52:9a6b" traceroute6(waypoint, minttl=10, maxttl=40, l4=IPv6ExtHdrRouting(addresses=[target])/ICMPv6EchoRequest(data=RandString(7)))

Using a DNS traceroute by specifying a complete packet in the l4 parameter of traceroute() function you don't get same IP addresses for all the hops.

from scapy.all import * target = ["172.217.17.46"] result, unans = traceroute(target, l4=UDP(sport=RandShort())/DNS(qd=DNSQR(qname="www.google.com")))
from scapy.all import * target = ["172.217.17.46"] result, unans = sr(IP(dst=target, ttl=(1, 10)) / TCP(dport=53, flags="S")) for snd, rcv in result: print(snd.ttl, rcv.src, snd.sent_time, rcv.time)
from scapy.all import * hostname = "172.217.17.46" for i in range(1, 28): pkt = IP(dst=hostname, ttl=i) / UDP(dport=33434) reply = sr1(pkt, verbose=0) if reply is None: break elif reply.type == 3: print("Done!", reply.src) break else: print("%d hops away: " % i, reply.src, reply.time)
  • Check out webb . I haven't use it, but you can use it like this:
import webb webb.traceroute("www.google.com") webb.traceroute("www.google.com",'file-name.txt')

Also, check out this tcptraceroute by Thomas Guettler.

Or this Multi-source traceroute with geolocation implementation by Addy Yeow (Ayeowch). Among other things, using -j parameter (JSON_FILE), it will list sources in JSON file format.

Or this implementation by Christian Kreibich. It can parse traceroute info into a series of hop objects, each consisting of one or more probe results, likewise, object instances. Also, string formatting produces familiar traceroute output. (In order to work with Python 3 one needs to change cStringIO to from io import StringIO

Without scapy (using windows console):

Create a script named output.py containing the following:
Example usage: python output.py ping google.com
Example output for ping :
Pinging google.com [216.58.209.14] with 32 bytes of data: Reply from 216.58.209.14: bytes=32 time=50ms TTL=56 Reply from 216.58.209.14: bytes=32 time=45ms TTL=56 Reply from 216.58.209.14: bytes=32 time=45ms TTL=56 Reply from 216.58.209.14: bytes=32 time=45ms TTL=56 Ping statistics for 216.58.209.14: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 45ms, Maximum = 50ms, Average = 46ms
Example usage: python output.py tracert google.com Example output for tracert : Tracing route to google.com [172.217.18.174] over a maximum of 30 hops: 1 <1 ms 1 ms 1 ms 192.168.0.1 2 6 ms 8 ms 8 ms xx.xx.xx.xx 3 8 ms 8 ms 8 ms [xx.xx.xxx.xxx] 4 17 ms 16 ms 16 ms be3549.ccr31.sof02.atlas.cogentco.com [154.54.59.138] 5 18 ms 17 ms 20 ms be3421.ccr51.beg03.atlas.cogentco.com [130.117.0.94] 6 32 ms 31 ms 30 ms be3464.ccr52.vie01.atlas.cogentco.com [154.54.59.189] 7 39 ms 37 ms 44 ms be3462.ccr22.muc03.atlas.cogentco.com [154.54.59.182] 8 42 ms 48 ms 44 ms be2960.ccr42.fra03.atlas.cogentco.com [154.54.36.253] 9 44 ms 50 ms 50 ms be3187.agr41.fra03.atlas.cogentco.com [130.117.1.117] 10 43 ms 45 ms 46 ms tata.fra03.atlas.cogentco.com [130.117.15.86] 11 45 ms 45 ms 44 ms 72.14.196.162 12 43 ms 41 ms 46 ms 108.170.251.129 13 46 ms 46 ms 45 ms 74.125.37.167 14 45 ms 52 ms 48 ms fra15s29-in-f14.1e100.net [172.217.18.174]

You can use tracert -d if you don't want names to be resolved.

Panos Kalatzantonakis's user avatar

  • A ping and a traceroute are not quite the same :/ –  Cukic0d Commented Nov 2, 2018 at 11:33
  • Do you have some updated code for 2021 please? I cannot get any of your code snippets to run on Python 3.8 on MacOS. –  Monty Commented Apr 13, 2021 at 4:59
  • It's not a Python version issue. It's scapy version. I have just tested my snippets using Python 3.7.7, 3.81, and works fine with scapy 2.4.3. Using the latest scapy documentation their examples do not work! –  Panos Kalatzantonakis Commented Apr 14, 2021 at 6:28

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python scapy traceroute or ask your own question .

  • The Overflow Blog
  • Masked self-attention: How LLMs learn relationships between tokens
  • Deedy Das: from coding at Meta, to search at Google, to investing with Anthropic
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Feedback Requested: How do you use the tagged questions page?

Hot Network Questions

  • Why does Voyager use consumable hydrazine instead of reaction wheels that only rotate when moving the spacecraft?
  • Estimating an upper bound of hyperbolicity constants in Gromov-hyperbolic groups
  • How to format units inside math environment?
  • YA sci fi book, tower on a planet with a destructive wind
  • Do pilots have to produce their pilot license to police when asked?
  • Does history possess the epistemological tools to establish the occurrence of an anomaly in the past that defies current scientific models?
  • What happened with the 31.5 ft giant in Jubbulpore district (now Jabalpur), India, August 8, 1934?
  • Does copying files from one drive to another also copy previously deleted data from the drive one?
  • How can I make second argument path relative to the first on a command?
  • Five Hundred Cigarettes
  • What is a "derivative security"?
  • Short novel where kids travel through tiny parallel universe
  • Are file attachments in email safe for transferring financial documents?
  • Neil Tyson: gravity is the same every where on the geoid
  • In John 3:16, what is the significance of Jesus' distinction between the terms 'world' and 'everyone who believes' within the context?
  • What book is this proof from?
  • Problems regressing y on x/y?
  • Can you find a grand tour of the rooms in this 12x12 grid?
  • How to fix bottom of stainless steel pot that has been separated from its main body?
  • Do mathematicians care about the validity ("truth") of the axioms?
  • What is an "axiomatic definition"? Every definition is an axiomatic definition?
  • Will a car seat fit into a standard economy class seat on a plane?
  • Is there a fast/clever way to return a logical vector if elements of a vector are in at least one interval?
  • How similar were the MC6800 and MOS 6502?

python programming assignment 4 traceroute

IMAGES

  1. Traceroute Command in Python and How to Read It

    python programming assignment 4 traceroute

  2. Traceroute Implementation on Python

    python programming assignment 4 traceroute

  3. Traceroute Command in Python and How to Read It

    python programming assignment 4 traceroute

  4. Traceroute Command in Python and How to Read It

    python programming assignment 4 traceroute

  5. A pure python interpretation of traceroute

    python programming assignment 4 traceroute

  6. Traceroute Implementation on Python

    python programming assignment 4 traceroute

VIDEO

  1. Starting Out With Python Chapter 4 Exercises Program 4 Distance travelled Python Program

  2. NPTEL Week 03

  3. NPTEL Programming In Java Week 9 Programming Assignment 4 Answers l March 2024

  4. How to use traceroute network command #shorts #ytshorts #linux #shortvideo

  5. C Network Programming

  6. Nptel

COMMENTS

  1. Traceroute Implementation on Python

    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 ...

  2. How to create an ICMP traceroute in Python

    Main point to remember is that traceroutes work by setting the TTL so if the solution is to use an ICMP library then it needs to have a configurable TTL :-) dest_addr = socket.gethostbyname(dest_name) port = 33434. max_hops = 30. icmp = socket.getprotobyname('icmp') udp = socket.getprotobyname('udp') ttl = 1.

  3. CSC 249

    CSC 249 Programming Project 4 - DIY Ping and Traceroute - bcheikes/csc-249-p4-diy-ping-traceroute. ... In this assignment, you will gain a better understanding of Internet Control Message Protocol ... Your task is to develop your own traceroute application in Python using ICMP. Your application will use ICMP but again, in order to keep it ...

  4. How can I perform a ping or traceroute in python, accessing the output

    However because python is not running as root it doens't have the ability to open the raw ICMP sockets needed to perform the ping/traceroute in native python. This brings me back to using the system's ping/traceroute shell commands. This question has a couple examples using the subprocess module which seem to work well: Ping a site in Python?

  5. How can I perform a ping or traceroute using native python?

    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:

  6. potraceroute

    FEATURES. single Python file runs on Linux, MacOS, NetBSD, FreeBSD, OpenBSD, Solaris, Windows 10, Android (root access needed, tested on LineageOS 14.1 with QPython 2.5.0) and AIX. supports TCP/UDP/ICMP traceroute. runs under Python 2.7 or Python 3. says what kind of traceroute is being run and to what port, so there's less chance of ...

  7. Implementing a simple traceroute clone in Python

    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.

  8. Implementation of traceroute in Python

    Notifications You must be signed in to change notification settings Implementation of traceroute in Python 3.x using raw sockets. Note that ICMP messages can only be sent from processes running as root (in Windows, you must run this script as 'Administrator'). Derived from Python's pyping library ...

  9. 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 ...

  10. pytraceroute · PyPI

    pytraceroute - A simple traceroute(8) implementation in Python. pytraceroute is a simple traceroute(8) implementation written in Python. Its purpose is mainly educational, rather than something feature-rich as is traceroute(8) for example. Requirements. Python 2.7.x or 3.x; docopt;

  11. Traceroute Command in Python and How to Read It

    Python. 1. 1. sudo ip2tracepy 8.8.8.8 -d DB25.BIN. See the result below: * By default, IP2Trace returns the country code, region, and city when data is available. Each line is a host or hops along ...

  12. Trace route implementation in python

    I have been trying to write a simple trace route implementation for python; please find the code below. import socket. def main (HostName): dest_addr = socket.gethostbyname(HostName) TTL = 1 #Define the time to live as 1. Will be incremented by one after each UDP message has been sent. Max = 30.

  13. Network Troubleshooting Techniques: Ping, Traceroute, PathPing

    Network Troubleshooting is a way to maintain your computer network, ensuring optimal performance, and addressing issues that may disrupt connectivity. when any problems arise, network administrators and IT professionals use tools such as Ping, Traceroute, and PathPing to identify and solve a problem. Ping is a command that sends a small packet ...

  14. pytraceroute

    A simple traceroute(8) implementation in Python 28 stars 13 forks Branches Tags Activity. Star Notifications You must be signed in to change notification settings. Code; Issues 1; Pull requests 0; Actions; Projects 0; Wiki; Security; Insights dnaeon/pytraceroute. This commit does not belong to any branch on this repository, and may belong to a ...

  15. Lab 6

    Task 6. Task 7. Task 8. Summary. 50.005 Computer System Engineering Information Systems Technology and Design Singapore University of Technology and Design Natalie Agus (Summer 2024) Ping and Traceroute. In this lab exercise, you will learn how to use ping and traceroute programs to measure round trip times and find network routes.

  16. GitHub

    Traceroute is a networking tool designed for tracing the movement of packets across a network. In this Python 3 implementation, ICMP 'ping' packets are used, much like the Windows tracert.exe program (and unlike Unix tracert which typically uses UDP packets). The application sends a sequence of ICMP packets to the host, initially with the Time-To-Live field set to 1.

  17. Socket Programming Assignment 5: ICMP Pinger · GitHub

    Socket Programming Assignment 5: ICMP Pinger. return "Request timed out." return "Request timed out." # Make a dummy header with a 0 checksum. # Calculate the checksum on the data and the dummy header. #Convert 16-bit integers from host to network byte order. #SOCK_RAW is a powerful socket type.

  18. Creating an ICMP traceroute in Python

    # Assume ip[] already has a full IP header. ver = struct.unpack("!B", ip[0])[0] # This produces the integer 4, which is required for sending IPV4 ver >> 4 In a nutshell, I've right-shifted a one-byte value down 4 bits. In this downshift, the new value compared to the old value now looks like this:

  19. trace

    trace. — Trace or track Python statement execution. ¶. Source code: Lib/trace.py. The trace module allows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.

  20. Tracert

    destination IP or hostname you want to trace. options: -h, --help show this help message and exit. -4 Force IPv4. -6 Force IPv6. --timeout TIMEOUT, -t TIMEOUT. Timeout for each ping. --retry RETRY, -r RETRY. Number of retry for each steps.

  21. python

    This project will require using Python to create a command line tool that automatically executes traceroute multiple times towards a target domain name or IP address specified as command line parameter. Based on multiple traceroute executions, the program will need to derive latency statistics for each hop between the traceroute client and the ...

  22. scapy

    I am writing a python script to perform 'TCP Traceroute'. I learned scapy is a useful library to do this but I`m not getting the results I need. ... I am using linux, python 2.7 with scapy 2.4. I am not sure why same ip addresses are shown for all the hops. from scapy.layers.inet import traceroute result, unans = traceroute('172.217.17.46 ...