Python Encyclopedia for Academics
  • Course Outline
  • Artificial Intelligence
    • Data Science Foundation
      • Python Programming
        • Introduction and Basics
          • Variables
          • Print Function
          • Input From User
          • Data Types
          • Type Conversion
        • Operators
          • Arithmetic Operators
          • Relational Operators
          • Bitwise Operators
          • Logical Operators
          • Assignment Operators
          • Compound Operators
          • Membership Operators
          • Identity Operators
      • Numpy
        • Vectors, Matrix
        • Operations on Matrix
        • Mean, Variance, and Standard Deviation
        • Reshaping Arrays
        • Transpose and Determinant of Matrix
      • Pandas
        • Series and DataFrames
        • Slicing, Rows, and Columns
        • Operations on DataFrames
        • Different wayes to creat DataFrame
        • Read, Write Operations with CSV files
      • Matplotlib
        • Graph Basics
        • Format Strings in Plots
        • Label Parameters, Legend
        • Bar Chart, Pie Chart, Histogram, and Scatter Plot
  • Machine Learning Algorithms
    • Regression Analysis In ML
      • Regression Analysis in Machine Learning
      • Proof of Linear Regression Formulas
      • Simple Linear Regression Implementation
      • Multiple Linear Regression
      • Advertising Dataset Example
      • Bike Sharing Dataset
      • Wine Quality Dataset
      • Auto MPG Dataset
    • Classification Algorithms in ML
      • Proof of Logistic Regression
      • Simplified Mathematical Proof of SVM
      • Iris Dataset
  • Machine Learning Laboratory
    • Lab 1: Titanic Dataset
      • Predicting Survival on the Titanic with Machine Learning
    • Lab 2: Dow Jones Index Dataset
      • Dow Jones Index Predictions Using Machine Learning
    • Lab 3: Diabetes Dataset
      • Numpy
      • Pandas
      • Matplotlib
      • Simple Linear Regression
      • Simple Non-linear Regression
      • Performance Matrix
      • Preprocessing
      • Naive Bayes Classification
      • K-Nearest Neighbors (KNN) Classification
      • Decision Tree & Random Forest
      • SVM Classifier
      • Logistic Regression
      • Artificial Neural Network
      • K means Clustering
    • Lab 4: MAGIC Gamma Telescope Dataset
      • Classification in ML-MAGIC Gamma Telescope Dataset
    • Lab 5: Seoul Bike Sharing Demand Dataset
      • Regression in ML-Seoul Bike Sharing Demand Dataset
    • Lab 6: Medical Cost Personal Datasets
      • Predict Insurance Costs with Linear Regression in Python
    • Lab 6: Predict The S&P 500 Index With Machine Learning And Python
      • Predict The S&P 500 Index With Machine Learning And Python
  • Artificial Neural Networks
    • Biological Inspiration vs. Artificial Neurons
    • Review linear algebra and calculus essentials for ANNs
    • Activation Function
  • Mathematics
    • Pre-Calculus
      • Factorials
      • Roots of Polynomials
      • Complex Numbers
      • Polar Coordinates
      • Graph of a Function
    • Calculus 1
      • Limit of a Function
      • Derivative of Function
      • Critical Points
      • Indefinite Integrals
  • Calculus 2
    • 3D Coordinates and Vectors
    • Vectors and Vector Operations
    • Lines and Planes in Space (3D)
    • Partial Derivatives
    • Optimization Problems (Maxima/Minima) in Multivariable Functions
    • Gradient Vectors
  • Engineering Mathematics
    • Laplace Transform
  • Electrical & electronics Eng
    • Resistor
      • Series Resistors
      • Parallel Resistors
    • Nodal Analysis
      • Example 1
      • Example 2
    • Transient State
      • RC Circuit Equations in the s-Domain
      • RL Circuit Equations in the s-Domain
      • LC Circuit Equations in the s-Domain
      • Series RLC Circuit with DC Source
  • Computer Networking
    • Fundamental
      • IPv4 Addressing
      • Network Diagnostics
  • Cybersecurity
    • Classical Ciphers
      • Caesar Cipher
      • Affine Cipher
      • Atbash Cipher
      • Vigenère Cipher
      • Gronsfeld Cipher
      • Alberti Cipher
      • Hill Cipher
Powered by GitBook
On this page
  • 1. Setting Up Your Environment
  • 2. Using Python for Ping
  • Step 3: Verbose Ping (optional)
  • Step 4: Error handling (optional)
  • 3. Using Python for Traceroute
  • Step 3: Display Results
  • 4. Complete Example: Combining Ping and Traceroute
  • 5. Advanced Usage: Customizing Ping and Traceroute
  • 6. Error Handling and Troubleshooting
  • Conclusion
  1. Computer Networking
  2. Fundamental

Network Diagnostics

Nerd Cafe

To use Python for network diagnostics like ping and traceroute, we can make use of built-in and external Python libraries. I'll guide you through the process step by step.

1. Setting Up Your Environment

First, ensure you have Python installed on your system. You will also need to install external libraries like ping3 and scapy for network diagnostics.

To install the necessary libraries, use pip:

pip install ping3 scapy

2. Using Python for Ping

The ping3 library is a lightweight tool for performing a "ping" to check the availability of a host.

Step 1: Import the required library

from ping3 import ping, verbose_ping

Step 2: Ping a server (e.g., Google's DNS server)

# Ping a host (IP or domain)

response = ping('8.8.8.8')
print(f"Ping response time: {response} seconds")

The output is:

Ping response time: 0.14790630340576172 seconds
  • ping('8.8.8.8'): Pings Google's DNS server at IP 8.8.8.8.

  • The result will be the time in seconds it took for the packet to reach the server and come back.

Step 3: Verbose Ping (optional)

To ping the host multiple times and display more information:

verbose_ping('8.8.8.8', count=4)  # Ping 4 times with verbose output

The output is:

ping '8.8.8.8' ... 48ms
ping '8.8.8.8' ... 42ms
ping '8.8.8.8' ... 47ms
ping '8.8.8.8' ... 43ms

Step 4: Error handling (optional)

You can add error handling to manage exceptions if the network is unreachable.

try:
    response = ping('172.16.11.20')
    if response is None:
        print("Host is unreachable.")
    else:
        print(f"Ping response time: {response} seconds")
except Exception as e:
    print(f"Error: {e}")

The output is:

Host is unreachable.

3. Using Python for Traceroute

For traceroute, we can use the scapy library to implement a simple version of it. Traceroute is used to trace the path packets take to reach a destination.

Step 1: Import the necessary library

from scapy.all import traceroute

Step 2: Run a traceroute

# Perform a traceroute
result, _ = traceroute(['www.google.com'], verbose=True)

The output is:

Received 45 packets, got 29 answers, remaining 1 packets
   216.239.38.120:tcp80 
1  192.168.1.1     11   
2  100.123.0.1     11   
3  172.19.16.33    11   
4  172.19.17.214   11   
5  172.19.17.209   11   
6  172.19.17.161   11   
7  172.19.17.37    11   
8  10.202.6.184    11   
9  10.21.212.10    11   
10 10.21.21.10     11   
12 213.202.5.239   11   
13 216.239.48.133  11   
14 192.178.87.255  11   
15 216.239.38.120  SA   
16 216.239.38.120  SA   
17 216.239.38.120  SA   
18 216.239.38.120  SA   
19 216.239.38.120  SA   
20 216.239.38.120  SA   
21 216.239.38.120  SA   
22 216.239.38.120  SA   
23 216.239.38.120  SA   
24 216.239.38.120  SA   
25 216.239.38.120  SA   
26 216.239.38.120  SA   
27 216.239.38.120  SA   
28 216.239.38.120  SA   
29 216.239.38.120  SA   
30 216.239.38.120  SA   
  • traceroute(): It sends packets with incremented TTL values to trace the route taken by packets to reach the destination.

Step 3: Display Results

The result will show each hop the packet takes to reach the destination.

4. Complete Example: Combining Ping and Traceroute

You can combine both functions (Ping and Traceroute) into a single script for better network diagnostics.

from ping3 import ping, verbose_ping
from scapy.all import traceroute

def network_diagnostics():
    # Ping Test
    print("Starting Ping Test:")
    ping_result = ping('8.8.8.8')
    if ping_result is None:
        print("Host is unreachable.")
    else:
        print(f"Ping response time: {ping_result} seconds")
    
    print("\nStarting Traceroute Test:")
    result, _ = traceroute(['www.google.com'], verbose=True)

if __name__ == '__main__':
    network_diagnostics()

The output is:

Starting Ping Test:
Ping response time: 0.045973777770996094 seconds

Starting Traceroute Test:

Received 30 packets, got 30 answers, remaining 0 packets
   216.239.38.120:tcp80 
1  192.168.1.1     11   
2  100.123.0.1     11   
3  172.19.16.33    11   
4  172.19.17.214   11   
5  172.19.17.209   11   
6  172.19.17.161   11   
7  172.19.17.37    11   
8  10.202.6.184    11   
9  10.21.212.10    11   
10 10.21.21.10     11   
11 134.0.220.186   11   
12 213.202.5.239   11   
13 216.239.48.87   11   
14 108.170.233.243 11   
15 216.239.38.120  SA   
16 216.239.38.120  SA   
17 216.239.38.120  SA   
18 216.239.38.120  SA   
19 216.239.38.120  SA   
20 216.239.38.120  SA   
21 216.239.38.120  SA   
22 216.239.38.120  SA   
23 216.239.38.120  SA   
24 216.239.38.120  SA   
25 216.239.38.120  SA   
26 216.239.38.120  SA   
27 216.239.38.120  SA   
28 216.239.38.120  SA   
29 216.239.38.120  SA   
30 216.239.38.120  SA   

5. Advanced Usage: Customizing Ping and Traceroute

You can also customize the behavior of ping and traceroute:

  • Ping timeout: By default, the ping3 library uses a timeout of 1 second. You can change this using ping('host', timeout=2) for a 2-second timeout.

  • Traceroute max hops: The scapy library's traceroute function has a max_hops parameter that you can adjust.

result, _ = traceroute(['www.google.com'], verbose=True, maxttl=20)

The output is:

Received 25 packets, got 19 answers, remaining 1 packets
   216.239.38.120:tcp80 
1  192.168.1.1     11   
2  100.123.0.1     11   
3  172.19.16.33    11   
4  172.19.17.214   11   
5  172.19.17.209   11   
6  172.19.17.161   11   
7  172.19.17.37    11   
8  10.202.6.186    11   
9  10.21.212.10    11   
10 10.21.21.10     11   
12 213.202.5.239   11   
13 216.239.48.87   11   
14 192.178.96.7    11   
15 216.239.38.120  SA   
16 216.239.38.120  SA   
17 216.239.38.120  SA   
18 216.239.38.120  SA   
19 216.239.38.120  SA   
20 216.239.38.120  SA   

6. Error Handling and Troubleshooting

For robust code, it's good practice to handle possible exceptions and errors:

  • Ping errors: Ensure the host is reachable before pinging.

  • Traceroute errors: Handle issues if scapy cannot perform the traceroute due to permissions or network issues.

try:
    ping_result = ping('8.8.8.8')
    if ping_result is None:
        print("Host is unreachable.")
    else:
        print(f"Ping response time: {ping_result} seconds")
except Exception as e:
    print(f"Ping Error: {e}")

try:
    result, _ = traceroute(['www.google.com'], verbose=True)
except Exception as e:
    print(f"Traceroute Error: {e}")

The output is:

Ping response time: 0.046968936920166016 seconds

Received 45 packets, got 29 answers, remaining 1 packets
   216.239.38.120:tcp80 
1  192.168.1.1     11   
2  100.123.0.1     11   
3  172.19.16.33    11   
4  172.19.17.214   11   
5  172.19.17.209   11   
6  172.19.17.161   11   
7  172.19.17.37    11   
8  10.202.6.188    11   
9  10.21.212.10    11   
10 10.21.21.10     11   
12 213.202.5.239   11   
13 216.239.48.87   11   
14 72.14.239.49    11   
15 216.239.38.120  SA   
16 216.239.38.120  SA   
17 216.239.38.120  SA   
18 216.239.38.120  SA   
19 216.239.38.120  SA   
20 216.239.38.120  SA   
21 216.239.38.120  SA   
22 216.239.38.120  SA   
23 216.239.38.120  SA   
24 216.239.38.120  SA   
25 216.239.38.120  SA   
26 216.239.38.120  SA   
27 216.239.38.120  SA   
28 216.239.38.120  SA   
29 216.239.38.120  SA   
30 216.239.38.120  SA   

Conclusion

By using Python libraries like ping3 and scapy, you can easily perform network diagnostics like ping and traceroute. This helps you monitor and troubleshoot network issues effectively.

PreviousIPv4 AddressingNextClassical Ciphers

Last updated 1 month ago