|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +""" |
| 4 | + A pure python ping implementation using raw socket. |
| 5 | +
|
| 6 | +
|
| 7 | + Note that ICMP messages can only be sent from processes running as root. |
| 8 | +
|
| 9 | +
|
| 10 | + Derived from ping.c distributed in Linux's netkit. That code is |
| 11 | + copyright (c) 1989 by The Regents of the University of California. |
| 12 | + That code is in turn derived from code written by Mike Muuss of the |
| 13 | + US Army Ballistic Research Laboratory in December, 1983 and |
| 14 | + placed in the public domain. They have my thanks. |
| 15 | +
|
| 16 | + Bugs are naturally mine. I'd be glad to hear about them. There are |
| 17 | + certainly word - size dependenceies here. |
| 18 | +
|
| 19 | + Copyright (c) Matthew Dixon Cowles, <http://www.visi.com/~mdc/>. |
| 20 | + Distributable under the terms of the GNU General Public License |
| 21 | + version 2. Provided with no warranties of any sort. |
| 22 | +
|
| 23 | + Original Version from Matthew Dixon Cowles: |
| 24 | + -> ftp://ftp.visi.com/users/mdc/ping.py |
| 25 | +
|
| 26 | + Rewrite by Jens Diemer: |
| 27 | + -> http://www.python-forum.de/post-69122.html#69122 |
| 28 | +
|
| 29 | + Rewrite by George Notaras: |
| 30 | + -> http://www.g-loaded.eu/2009/10/30/python-ping/ |
| 31 | +
|
| 32 | + Fork by Pierre Bourdon: |
| 33 | + -> http://bitbucket.org/delroth/python-ping/ |
| 34 | +
|
| 35 | + Revision history |
| 36 | + ~~~~~~~~~~~~~~~~ |
| 37 | +
|
| 38 | + November 22, 1997 |
| 39 | + ----------------- |
| 40 | + Initial hack. Doesn't do much, but rather than try to guess |
| 41 | + what features I (or others) will want in the future, I've only |
| 42 | + put in what I need now. |
| 43 | +
|
| 44 | + December 16, 1997 |
| 45 | + ----------------- |
| 46 | + For some reason, the checksum bytes are in the wrong order when |
| 47 | + this is run under Solaris 2.X for SPARC but it works right under |
| 48 | + Linux x86. Since I don't know just what's wrong, I'll swap the |
| 49 | + bytes always and then do an htons(). |
| 50 | +
|
| 51 | + December 4, 2000 |
| 52 | + ---------------- |
| 53 | + Changed the struct.pack() calls to pack the checksum and ID as |
| 54 | + unsigned. My thanks to Jerome Poincheval for the fix. |
| 55 | +
|
| 56 | + May 30, 2007 |
| 57 | + ------------ |
| 58 | + little rewrite by Jens Diemer: |
| 59 | + - change socket asterisk import to a normal import |
| 60 | + - replace time.time() with time.clock() |
| 61 | + - delete "return None" (or change to "return" only) |
| 62 | + - in checksum() rename "str" to "source_string" |
| 63 | +
|
| 64 | + November 8, 2009 |
| 65 | + ---------------- |
| 66 | + Improved compatibility with GNU/Linux systems. |
| 67 | +
|
| 68 | + Fixes by: |
| 69 | + * George Notaras -- http://www.g-loaded.eu |
| 70 | + Reported by: |
| 71 | + * Chris Hallman -- http://cdhallman.blogspot.com |
| 72 | +
|
| 73 | + Changes in this release: |
| 74 | + - Re-use time.time() instead of time.clock(). The 2007 implementation |
| 75 | + worked only under Microsoft Windows. Failed on GNU/Linux. |
| 76 | + time.clock() behaves differently under the two OSes[1]. |
| 77 | +
|
| 78 | + [1] http://docs.python.org/library/time.html#time.clock |
| 79 | +
|
| 80 | + September 25, 2010 |
| 81 | + ------------------ |
| 82 | + Little modifications by Georgi Kolev: |
| 83 | + - Added quiet_ping function. |
| 84 | + - returns percent lost packages, max round trip time, avrg round trip |
| 85 | + time |
| 86 | + - Added packet size to verbose_ping & quiet_ping functions. |
| 87 | + - Bump up version to 0.2 |
| 88 | +
|
| 89 | +""" |
| 90 | + |
| 91 | +__version__ = "0.2" |
| 92 | + |
| 93 | +import os |
| 94 | +import select |
| 95 | +import socket |
| 96 | +import struct |
| 97 | +import sys |
| 98 | +import time |
| 99 | + |
| 100 | +# From /usr/include/linux/icmp.h; your milage may vary. |
| 101 | +ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris. |
| 102 | + |
| 103 | + |
| 104 | +def checksum(source_string): |
| 105 | + """ |
| 106 | + I'm not too confident that this is right but testing seems |
| 107 | + to suggest that it gives the same answers as in_cksum in ping.c |
| 108 | + """ |
| 109 | + sum = 0 |
| 110 | + count_to = (len(source_string) / 2) * 2 |
| 111 | + for count in xrange(0, count_to, 2): |
| 112 | + this = ord(source_string[count + 1]) * 256 + ord(source_string[count]) |
| 113 | + sum = sum + this |
| 114 | + sum = sum & 0xffffffff # Necessary? |
| 115 | + |
| 116 | + if count_to < len(source_string): |
| 117 | + sum = sum + ord(source_string[len(source_string) - 1]) |
| 118 | + sum = sum & 0xffffffff # Necessary? |
| 119 | + |
| 120 | + sum = (sum >> 16) + (sum & 0xffff) |
| 121 | + sum = sum + (sum >> 16) |
| 122 | + answer = ~sum |
| 123 | + answer = answer & 0xffff |
| 124 | + |
| 125 | + # Swap bytes. Bugger me if I know why. |
| 126 | + answer = answer >> 8 | (answer << 8 & 0xff00) |
| 127 | + |
| 128 | + return answer |
| 129 | + |
| 130 | + |
| 131 | +def receive_one_ping(my_socket, id, timeout): |
| 132 | + """ |
| 133 | + Receive the ping from the socket. |
| 134 | + """ |
| 135 | + time_left = timeout |
| 136 | + while True: |
| 137 | + started_select = time.time() |
| 138 | + what_ready = select.select([my_socket], [], [], time_left) |
| 139 | + how_long_in_select = (time.time() - started_select) |
| 140 | + if what_ready[0] == []: # Timeout |
| 141 | + return |
| 142 | + |
| 143 | + time_received = time.time() |
| 144 | + received_packet, addr = my_socket.recvfrom(1024) |
| 145 | + icmpHeader = received_packet[20:28] |
| 146 | + type, code, checksum, packet_id, sequence = struct.unpack( |
| 147 | + "bbHHh", icmpHeader |
| 148 | + ) |
| 149 | + if packet_id == id: |
| 150 | + bytes = struct.calcsize("d") |
| 151 | + time_sent = struct.unpack("d", received_packet[28:28 + bytes])[0] |
| 152 | + return time_received - time_sent |
| 153 | + |
| 154 | + time_left = time_left - how_long_in_select |
| 155 | + if time_left <= 0: |
| 156 | + return |
| 157 | + |
| 158 | + |
| 159 | +def send_one_ping(my_socket, dest_addr, id, psize): |
| 160 | + """ |
| 161 | + Send one ping to the given >dest_addr<. |
| 162 | + """ |
| 163 | + dest_addr = socket.gethostbyname(dest_addr) |
| 164 | + |
| 165 | + # Remove header size from packet size |
| 166 | + psize = psize - 8 |
| 167 | + |
| 168 | + # Header is type (8), code (8), checksum (16), id (16), sequence (16) |
| 169 | + my_checksum = 0 |
| 170 | + |
| 171 | + # Make a dummy heder with a 0 checksum. |
| 172 | + header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, id, 1) |
| 173 | + bytes = struct.calcsize("d") |
| 174 | + data = (psize - bytes) * "Q" |
| 175 | + data = struct.pack("d", time.time()) + data |
| 176 | + |
| 177 | + # Calculate the checksum on the data and the dummy header. |
| 178 | + my_checksum = checksum(header + data) |
| 179 | + |
| 180 | + # Now that we have the right checksum, we put that in. It's just easier |
| 181 | + # to make up a new header than to stuff it into the dummy. |
| 182 | + header = struct.pack( |
| 183 | + "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), id, 1 |
| 184 | + ) |
| 185 | + packet = header + data |
| 186 | + my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 |
| 187 | + |
| 188 | + |
| 189 | +def do_one(dest_addr, timeout, psize): |
| 190 | + """ |
| 191 | + Returns either the delay (in seconds) or none on timeout. |
| 192 | + """ |
| 193 | + icmp = socket.getprotobyname("icmp") |
| 194 | + try: |
| 195 | + my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) |
| 196 | + except socket.error, (errno, msg): |
| 197 | + if errno == 1: |
| 198 | + # Operation not permitted |
| 199 | + msg = msg + ( |
| 200 | + " - Note that ICMP messages can only be sent from processes" |
| 201 | + " running as root." |
| 202 | + ) |
| 203 | + raise socket.error(msg) |
| 204 | + raise # raise the original error |
| 205 | + |
| 206 | + my_id = os.getpid() & 0xFFFF |
| 207 | + |
| 208 | + send_one_ping(my_socket, dest_addr, my_id, psize) |
| 209 | + delay = receive_one_ping(my_socket, my_id, timeout) |
| 210 | + |
| 211 | + my_socket.close() |
| 212 | + return delay |
| 213 | + |
| 214 | + |
| 215 | +def verbose_ping(dest_addr, timeout = 2, count = 4, psize = 64): |
| 216 | + """ |
| 217 | + Send `count' ping with `psize' size to `dest_addr' with |
| 218 | + the given `timeout' and display the result. |
| 219 | + """ |
| 220 | + for i in xrange(count): |
| 221 | + print "ping %s with ..." % dest_addr, |
| 222 | + try: |
| 223 | + delay = do_one(dest_addr, timeout, psize) |
| 224 | + except socket.gaierror, e: |
| 225 | + print "failed. (socket error: '%s')" % e[1] |
| 226 | + break |
| 227 | + |
| 228 | + if delay == None: |
| 229 | + print "failed. (timeout within %ssec.)" % timeout |
| 230 | + else: |
| 231 | + delay = delay * 1000 |
| 232 | + print "get ping in %0.4fms" % delay |
| 233 | + print |
| 234 | + |
| 235 | + |
| 236 | +def quiet_ping(dest_addr, timeout = 2, count = 4, psize = 64): |
| 237 | + """ |
| 238 | + Send `count' ping with `psize' size to `dest_addr' with |
| 239 | + the given `timeout' and display the result. |
| 240 | + Returns `percent' lost packages, `max' round trip time |
| 241 | + and `avrg' round trip time. |
| 242 | + """ |
| 243 | + mrtt = None |
| 244 | + artt = None |
| 245 | + lost = 0 |
| 246 | + plist = [] |
| 247 | + |
| 248 | + for i in xrange(count): |
| 249 | + try: |
| 250 | + delay = do_one(dest_addr, timeout, psize) |
| 251 | + except socket.gaierror, e: |
| 252 | + print "failed. (socket error: '%s')" % e[1] |
| 253 | + break |
| 254 | + |
| 255 | + if delay != None: |
| 256 | + delay = delay * 1000 |
| 257 | + plist.append(delay) |
| 258 | + |
| 259 | + # Find lost package percent |
| 260 | + percent_lost = 100 - (len(plist) * 100 / count) |
| 261 | + |
| 262 | + # Find max and avg round trip time |
| 263 | + if plist: |
| 264 | + mrtt = max(plist) |
| 265 | + artt = sum(plist) / len(plist) |
| 266 | + |
| 267 | + return percent_lost, mrtt, artt |
| 268 | + |
| 269 | +if __name__ == '__main__': |
| 270 | + verbose_ping("heise.de") |
| 271 | + verbose_ping("google.com") |
| 272 | + verbose_ping("a-test-url-taht-is-not-available.com") |
| 273 | + verbose_ping("192.168.1.1") |
0 commit comments