Certainly! Below is a Python script for a powerful and professional ping test tool. This tool allows you to ping multiple hosts simultaneously, measure round-trip times, and display statistics similar to the standard ping command. It uses raw sockets to send ICMP Echo Requests, which requires administrator privileges to run.
import socket
import struct
import time
import select
import sys
import threading
import argparse
ICMP_ECHO_REQUEST = 8
ICMP_CODE = socket.getprotobyname('icmp')
class PingStats:
def __init__(self):
self.sent = 0
self.received = 0
self.rtt_min = float('inf')
self.rtt_max = 0
self.rtt_sum = 0
self.rtt_sq_sum = 0
def update(self, rtt):
self.received += 1
self.rtt_min = min(self.rtt_min, rtt)
self.rtt_max = max(self.rtt_max, rtt)
self.rtt_sum += rtt
self.rtt_sq_sum += rtt ** 2
def checksum(source_string):
"""
Calculate the checksum of the input string.
"""
sum = 0
max_count = (len(source_string) // 2) * 2
count = 0
while count < max_count:
val = source_string[count + 1] * 256 + source_string[count]
sum += val
sum &= 0xffffffff
count += 2
if max_count < len(source_string):
sum += source_string[len(source_string) - 1]
sum &= 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum += (sum >> 16)
answer = ~sum & 0xffff
answer = socket.htons(answer)
return answer
def create_packet(id, sequence):
"""
Create a new echo request packet based on the given id and sequence number.
"""
header = struct.pack('!BBHHH', ICMP_ECHO_REQUEST, 0, 0, id, sequence)
data = struct.pack('d', time.time())
my_checksum = checksum(header + data)
header = struct.pack('!BBHHH', ICMP_ECHO_REQUEST, 0, my_checksum, id, sequence)
return header + data
def ping(host, count=4, timeout=1):
"""
Send ICMP echo requests to a specified host.
"""
try:
dest_addr = socket.gethostbyname(host)
except socket.gaierror:
print(f"Cannot resolve {host}: Unknown host")
return
print(f"PING {host} ({dest_addr}): {64} data bytes")
stats = PingStats()
id = threading.get_ident() & 0xFFFF
seq_number = 1
for _ in range(count):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, ICMP_CODE)
sock.settimeout(timeout)
except PermissionError:
print("Operation not permitted: You need administrator privileges to run this script.")
return
except Exception as e:
print(f"Socket error: {e}")
return
packet = create_packet(id, seq_number)
send_time = time.time()
try:
sock.sendto(packet, (dest_addr, 1))
stats.sent += 1
except socket.error as e:
print(f"General failure ({e})")
sock.close()
continue
delay = receive_ping(sock, id, timeout, send_time)
sock.close()
if delay is None:
print("Request timed out.")
else:
delay *= 1000 # Convert to milliseconds
stats.update(delay)
print(f"{64} bytes from {dest_addr}: icmp_seq={seq_number} ttl=64 time={delay:.3f} ms")
seq_number += 1
time.sleep(1)
# Print summary
stats_summary(host, stats)
def receive_ping(sock, id, timeout, send_time):
"""
Receive the ping from the socket.
"""
try:
while True:
start_time = time.time()
select_timeout = timeout - (start_time - send_time)
if select_timeout <= 0:
return None
ready = select.select([sock], [], [], select_timeout)
if ready[0] == []: # Timeout
return None
time_received = time.time()
rec_packet, addr = sock.recvfrom(1024)
icmp_header = rec_packet[20:28]
type, code, checksum_recv, packet_id, sequence = struct.unpack('!BBHHH', icmp_header)
if packet_id == id and type == 0: # ICMP Echo Reply
data_size = struct.calcsize('d')
time_sent = struct.unpack('d', rec_packet[28:28 + data_size])[0]
return time_received - time_sent
except socket.timeout:
return None
except Exception as e:
print(f"Receive failed: {e}")
return None
def stats_summary(host, stats):
"""
Print the ping statistics summary.
"""
lost = stats.sent - stats.received
loss = (lost / stats.sent) * 100 if stats.sent > 0 else 0
print(f"\n--- {host} ping statistics ---")
print(f"{stats.sent} packets transmitted, {stats.received} packets received, {loss:.1f}% packet loss")
if stats.received > 0:
rtt_avg = stats.rtt_sum / stats.received
rtt_mdev = ((stats.rtt_sq_sum / stats.received) - (rtt_avg ** 2)) ** 0.5
print(f"round-trip min/avg/max/stddev = {stats.rtt_min:.3f}/{rtt_avg:.3f}/{stats.rtt_max:.3f}/{rtt_mdev:.3f} ms")
def main():
parser = argparse.ArgumentParser(description='Powerful Ping Test Tool')
parser.add_argument('host', nargs='+', help='Host(s) to ping')
parser.add_argument('-c', '--count', type=int, default=4, help='Number of echo requests to send')
parser.add_argument('-t', '--timeout', type=int, default=1, help='Timeout in seconds to wait for each reply')
parser.add_argument('-p', '--parallel', action='store_true', help='Ping hosts in parallel')
args = parser.parse_args()
if args.parallel and len(args.host) > 1:
threads = []
for host in args.host:
thread = threading.Thread(target=ping, args=(host, args.count, args.timeout))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
else:
for host in args.host:
ping(host, args.count, args.timeout)
if __name__ == '__main__':
main()
Explanation
Imports and Constants
- Imports: The script imports necessary modules like
socket, struct, time, select, threading, and argparse.
- Constants: Defines
ICMP_ECHO_REQUEST and gets the protocol number for ICMP using socket.getprotobyname('icmp').
PingStats Class
- Purpose: Keeps track of statistics such as packets sent, received, minimum/maximum/average round-trip times (RTT), and RTT standard deviation.
- Methods:
__init__: Initializes statistical counters.
update: Updates statistics with the latest RTT measurement.
checksum() Function
- Purpose: Calculates the checksum of the packet header and data, which is required for ICMP packets.
- Methodology: Implements the Internet checksum algorithm.
create_packet() Function
- Purpose: Constructs the ICMP Echo Request packet with the appropriate headers and data.
- Headers:
- Type (8 bits):
ICMP_ECHO_REQUEST
- Code (8 bits): 0
- Checksum (16 bits): Calculated using the
checksum() function
- Identifier (16 bits): Unique ID for the packet, typically the thread ID
- Sequence Number (16 bits): Incremented with each packet
ping() Function
- Purpose: Manages the sending of Echo Requests and receiving of Echo Replies for a given host.
- Process:
- Resolves the host to an IP address.
- Prints the initial ping message.
- Enters a loop to send the specified number of packets.
- Creates a raw socket and sends an Echo Request.
- Waits for a reply using
receive_ping().
- Updates statistics and prints each reply's details.
- Sleeps for 1 second between each request.
- After the loop, calls
stats_summary() to print the statistics.
receive_ping() Function
- Purpose: Waits for an Echo Reply and calculates the RTT.
- Process:
- Uses
select.select to wait for the socket to become readable within the timeout.
- Receives the packet and extracts the ICMP header.
- Checks if the received packet is an Echo Reply matching the sent packet ID.
- Calculates RTT by comparing send and receive timestamps.
stats_summary() Function
- Purpose: Calculates and prints the summary statistics after all packets have been sent.
- Statistics:
- Packets transmitted and received
- Packet loss percentage
- Minimum, average, maximum, and standard deviation of RTTs
main() Function
- Purpose: Parses command-line arguments and initiates the ping process.
- Features:
- Supports pinging multiple hosts.
- Includes options for the number of packets (
-c), timeout (-t), and parallel execution (-p).
- If parallel execution is enabled, pings all hosts simultaneously using threads.
Permission Note
- Administrator Privileges: The script requires administrator privileges to create raw sockets for sending ICMP packets (e.g., use
sudo on Unix systems).
- Compatibility: May require adjustments on some operating systems due to security restrictions on raw sockets.
Usage Examples
-
Ping a Single Host:
python ping_test.py example.com
-
Ping Multiple Hosts Sequentially:
python ping_test.py example.com google.com
-
Ping Multiple Hosts in Parallel:
python ping_test.py example.com google.com -p
-
Specify Number of Echo Requests:
python ping_test.py example.com -c 10
-
Set a Custom Timeout:
python ping_test.py example.com -t 2
Enhancements
- Error Handling: The script includes error handling for hostname resolution and socket creation.
- Cross-Platform Support: Designed to work on both Unix and Windows systems, though Windows may have limitations on raw socket usage.
- Extendable: You can add features like logging to files, customizing packet sizes, or integrating with network monitoring tools.
Important Notes
- Administrator Privileges Required: Running this script requires administrator privileges due to the use of raw sockets.
- Operating System Limitations: Some operating systems may restrict raw socket operations or ICMP message sending.
- Use Responsibly: Be cautious when pinging hosts, especially those you do not own or manage, to avoid violating network policies or laws.
Conclusion
This powerful and professional Python ping test tool provides detailed network diagnostics and performance measurements. It's suitable for network administrators, engineers, or anyone needing advanced ping functionalities beyond basic tools.
Feel free to customize and enhance the script to suit your specific needs!