Skip to content

Instantly share code, notes, and snippets.

@cjhanks
Forked from anonymous/ping.py
Last active December 10, 2015 02:58
Show Gist options
  • Save cjhanks/4371454 to your computer and use it in GitHub Desktop.
Save cjhanks/4371454 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
A pure python ping implementation using raw socket.
Note that ICMP messages can only be sent from processes running as root.
Derived from ping.c distributed in Linux's netkit. That code is
copyright (c) 1989 by The Regents of the University of California.
That code is in turn derived from code written by Mike Muuss of the
US Army Ballistic Research Laboratory in December, 1983 and
placed in the public domain. They have my thanks.
Bugs are naturally mine. I'd be glad to hear about them. There are
certainly word - size dependenceies here.
Copyright (c) Matthew Dixon Cowles, <http://www.visi.com/~mdc/>.
Distributable under the terms of the GNU General Public License
version 2. Provided with no warranties of any sort.
Original Version from Matthew Dixon Cowles:
-> ftp://ftp.visi.com/users/mdc/ping.py
Rewrite by Jens Diemer:
-> http://www.python-forum.de/post-69122.html#69122
Rewrite by George Notaras:
-> http://www.g-loaded.eu/2009/10/30/python-ping/
Revision history
~~~~~~~~~~~~~~~~
November 22, 1997
-----------------
Initial hack. Doesn't do much, but rather than try to guess
what features I (or others) will want in the future, I've only
put in what I need now.
December 16, 1997
-----------------
For some reason, the checksum bytes are in the wrong order when
this is run under Solaris 2.X for SPARC but it works right under
Linux x86. Since I don't know just what's wrong, I'll swap the
bytes always and then do an htons().
December 4, 2000
----------------
Changed the struct.pack() calls to pack the checksum and ID as
unsigned. My thanks to Jerome Poincheval for the fix.
May 30, 2007
------------
little rewrite by Jens Diemer:
- change socket asterisk import to a normal import
- replace time.time() with time.clock()
- delete "return None" (or change to "return" only)
- in checksum() rename "str" to "source_string"
November 8, 2009
----------------
Improved compatibility with GNU/Linux systems.
Fixes by:
* George Notaras -- http://www.g-loaded.eu
Reported by:
* Chris Hallman -- http://cdhallman.blogspot.com
Changes in this release:
- Re-use time.time() instead of time.clock(). The 2007 implementation
worked only under Microsoft Windows. Failed on GNU/Linux.
time.clock() behaves differently under the two OSes[1].
[1] http://docs.python.org/library/time.html#time.clock
December 25, 2012
-----------------
Christopher J. Hanks <develop@cjhanks.name>
- Remove redundant operations and variables.
- Added TimeoutException for errors.
- Brought code much closer to PEP8 standard (9.55 / 10)
"""
#
# see: /usr/include/linux/icmp.h
# to understand 'magic numbers'
#
# struct icmphdr {
# __u8 type;
# __u8 code;
# __sum16 checksum;
# union {
# struct {
# __be16 id;
# __be16 sequence;
# } echo;
# struct {
# __be16 __unused;
# __be16 mtu;
# } frag;
# } un;
# }
#
from socket import (socket, gethostbyname, getprotobyname, htons, AF_INET,
SOCK_RAW)
from select import select
from os import getpid
from struct import pack, unpack, calcsize
from time import time
ICMP_ECHO_REQUEST = 8
class TimeoutException(RuntimeError):
"""
:class TimeoutException:
"""
def __init__(self, timeout, msg = ''):
RuntimeError.__init__(self, msg)
self.timeout = timeout
def _checksum(src):
"""
Checksum derived from in_cksum in ping.c
"""
sss = 0
count_to = int(len(src))
count = 0
while count < count_to:
sss += ord(src[count + 1]) * 256 + ord(src[count])
sss &= 0xffffffff
count += 2
if count_to < len(src):
sss += ord(src[-1:])
sss &= 0xffffffff
sss = (sss >> 16) + (sss & 0xffff)
sss += (sss >> 16)
ret = ~sss & 0xffff
ret = ret >> 8 | (ret << 8 & 0xff00)
return ret
def _recv_ping(sock, msg_id, timeout):
"""
Receive a single ping from the socket which has an ID matching msg_id
:param sock: Socket to act only
:type sock: socket.socket()
:param msg_id: Packet message ID to listen for.
:type msg_id: str()
:param timeout: Ping RTT timeout
:type timeout: int()
"""
select_wait = timeout
while True:
s_start = time()
s_stats = select([sock], [], [], select_wait)
s_time = time() - s_start
if not len(s_stats[0]):
raise TimeoutException(timeout)
t_recv = time()
recv_packet = sock.recvfrom(1024)[0]
icmp_header = recv_packet[20:28]
pkt_id = unpack('bbHHh', icmp_header)[3]
if pkt_id == msg_id:
return t_recv - unpack('d', recv_packet[28:28 + calcsize('d')])[0]
select_wait -= s_time
if select_wait <= 0:
raise TimeoutException(timeout)
def _send_ping(sock, dest, msg_id):
"""
Send a single ping.
:param sock: Socket to act only
:type sock: socket.socket()
:param dest: Destination to send to.
:type dest: str()
:param msg_id: Message id to send and watch for in return.
:type msg_id: str()
"""
# create faux header : create data item : create real header
header = pack('bbHHh', ICMP_ECHO_REQUEST, 0, 0, msg_id, 1)
msgdat = pack('d', time()) + ((192 - calcsize('d')) * 'Q')
header = pack(
'bbHHh', ICMP_ECHO_REQUEST, 0, htons(_checksum(header + msgdat)),
msg_id, 1
)
try:
sock.sendto(header + msgdat, (gethostbyname(dest), 1))
except Exception as (errno, errstr):
raise RuntimeError('errno = %i : %s' % (errno, errstr))
def _ping(destination, timeout):
"""
Implementation for single ping
:param destination: Location to send ping to.
:type destination: str()
:param timeout: Ping RTT timeout
:type timeout: int()
"""
try:
sock = socket(AF_INET, SOCK_RAW, getprotobyname('icmp'))
except tuple as (errno, msg):
if 1 == errno:
raise RuntimeError('uid != 0')
else:
raise RuntimeError('unknown error [%i]: %s' % (errno, msg))
msg_id = getpid() & 0xFFFF
_send_ping(sock, destination, msg_id)
period = _recv_ping(sock, msg_id, timeout)
sock.close()
return period * 1000
def ping(destination, timeout = 4, count = 1):
"""
Send ping(s) to a destination and return the mean RTT.
raises RuntimeError if ping times out.
:param destination: Web-address to ping.
:type destination: str()
:param timeout: Maximum timeout per-ping
:type timeout: int()
:param count: Number of pings to send and test
:type count: int()
:return: Mean round trip time in ms
:type : float()
"""
rets = list()
for _ in xrange(count):
rets.append(_ping(destination, timeout))
return sum(rets) / len(rets)
if __name__ == '__main__':
#
#Create a more useful basic test case
#
import sys
from time import sleep
if len(sys.argv) < 2:
print(
'Usage: ./ping.py hostname ping_count'
)
exit(1)
host = sys.argv[1]
cnt = 1 if len(sys.argv) < 3 else int(sys.argv[2])
try:
print(
'PING %s (%s)' % (host, gethostbyname(host))
)
except tuple as err:
print(
'PING %s (%s)' % (host, 'UNKNOWN HOST')
)
for i in xrange(cnt):
try:
print(
'icmp_req=%02i time=%03f ms' % (i, ping(host))
)
except TimeoutException as err:
print(
'icmp_req=%02i time=timeout' % i
)
except RuntimeError as err:
print(
'icmp_req=%02i time=ERROR [%s]' % (i, str(err))
)
sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment