From dbcd6e076518952bb06a3c00ba7aa6df4ca1073b Mon Sep 17 00:00:00 2001 From: Muhamed Fazal PS Date: Fri, 17 Jul 2026 13:42:15 +0530 Subject: [PATCH] fix: make ping.py compatible with Python 3 --- ping.py | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/ping.py b/ping.py index 73400fa..be9f3c0 100644 --- a/ping.py +++ b/ping.py @@ -72,8 +72,11 @@ import os, sys, socket, struct, select, time if sys.platform == "win32": - # On Windows, the best timer is time.clock() - default_timer = time.clock + # On Windows, the best timer is time.perf_counter() + if hasattr(time, "perf_counter"): + default_timer = time.perf_counter + else: + default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time @@ -87,18 +90,19 @@ def checksum(source_string): I'm not too confident that this is right but testing seems to suggest that it gives the same answers as in_cksum in ping.c """ + source_bytes = bytearray(source_string) sum = 0 - countTo = (len(source_string)/2)*2 + countTo = (len(source_bytes) // 2) * 2 count = 0 - while count> 16) + (sum & 0xffff) sum = sum + (sum >> 16) @@ -154,7 +158,7 @@ def send_one_ping(my_socket, dest_addr, ID): # Make a dummy heder with a 0 checksum. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) bytesInDouble = struct.calcsize("d") - data = (192 - bytesInDouble) * "Q" + data = (192 - bytesInDouble) * b"Q" data = struct.pack("d", default_timer()) + data # Calculate the checksum on the data and the dummy header. @@ -176,7 +180,8 @@ def do_one(dest_addr, timeout): icmp = socket.getprotobyname("icmp") try: my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) - except socket.error, (errno, msg): + except socket.error as e: + errno, msg = e.args[0], e.args[1] if len(e.args) > 1 else str(e) if errno == 1: # Operation not permitted msg = msg + ( @@ -200,20 +205,22 @@ def verbose_ping(dest_addr, timeout = 2, count = 4): Send >count< ping to >dest_addr< with the given >timeout< and display the result. """ - for i in xrange(count): - print "ping %s..." % dest_addr, + for i in range(count): + print("ping %s..." % dest_addr, end="") + sys.stdout.flush() try: delay = do_one(dest_addr, timeout) - except socket.gaierror, e: - print "failed. (socket error: '%s')" % e[1] + except socket.gaierror as e: + err_msg = e.args[1] if len(e.args) > 1 else str(e) + print("failed. (socket error: '%s')" % err_msg) break if delay == None: - print "failed. (timeout within %ssec.)" % timeout + print("failed. (timeout within %ssec.)" % timeout) else: delay = delay * 1000 - print "get ping in %0.4fms" % delay - print + print("get ping in %0.4fms" % delay) + print() if __name__ == '__main__':