{"id":39,"date":"2011-09-06T08:47:16","date_gmt":"2011-09-06T13:47:16","guid":{"rendered":"https:\/\/www.falatic.com\/?p=39"},"modified":"2015-05-28T11:35:29","modified_gmt":"2015-05-28T18:35:29","slug":"pinging-with-python","status":"publish","type":"post","link":"https:\/\/www.falatic.com\/index.php\/39\/pinging-with-python","title":{"rendered":"Pinging with Python"},"content":{"rendered":"<p><em>2015-05-28 update: Some of the old repos mentioned in this article are gone. You can check out <a href=\"https:\/\/github.com\/l4m3rx\/python-ping\" target=\"_blank\">Georgi Kolev&#8217;s repo<\/a> (which has been recently updated) or <a href=\"https:\/\/github.com\/MartyMacGyver\/python-ping\" target=\"_blank\">my older one<\/a>. Jens appears to have deleted his fork of this\u00a0<a href=\"https:\/\/pypi.python.org\/pypi\/python-ping\" target=\"_blank\">though you can find it in\u00a0Pypi<\/a>\u00a0(it&#8217;s outdated as well now).<\/em><\/p>\n<p><em>2011-10-12 update: Brought in more changes from <a href=\"https:\/\/github.com\/jedie\/python-ping\" target=\"_blank\">Jens Diemer&#8217;s new repository for the Python 2 version of this project<\/a>\u00a0[dead link].<br \/>\n<\/em><\/p>\n<p><em>2011-09-12 update: The version here is for Python 3.x as described below. <a href=\"https:\/\/github.com\/jedie\/python-code-snippets\/blob\/master\/CodeSnippets\/ping.py\" target=\"_blank\">Jens Diemer posted an updated version of this to GitHub<\/a> with corrections. It&#8217;s mainly a backport of this script to Python 2.x along with some cosmetic changes (and yes, I do like delimiting functions and such with comment lines &#8211; it makes code blocks far easier to distinguish, even in indentation-intensive Python). He added a bugfix to handle SIGBREAK better, which I&#8217;ve pulled into the code below.<br \/>\n<\/em><\/p>\n<p>A while back, when I decided to learn Python, I looked into writing my own sort of ping utility with it. Then I learned just how ridiculously arduous it is to perform this seemingly-simple function (essentially, you have to be running as root in Unix (or Administrator in Windows) to accomplish this, and generally speaking running scripts like this as root is considered bad form). But it can be done&#8230;<\/p>\n<p><!--more--><\/p>\n<p>This intrigued me as a pet project but I moved on to other things, eventually picking up Python along the way (I&#8217;ve focused on Python 3.x since the Unicode handling is FAR better than it is in 2.7, not to mention its other improvements).<\/p>\n<p>Recently, I decided to revisit the &#8220;ping with Python&#8221; idea, and searched around to see if anyone else had tackled it. Sure enough, <a href=\"http:\/\/www.g-loaded.eu\/2009\/10\/30\/python-ping\/\" target=\"_blank\">I found George Notaras&#8217; site<\/a> which has a very nice implementation in 2.x as well as a recent commenter who created a 3.x port. Only problem was, the HTML is mangled there so neither script worked. As I delved into it, I managed to get the scripts working, and then decided to go the extra mile and make some enhancements and improvements. Along the way I ended up getting the source for ping (via Cygwin) and building it from scratch as well (particularly to understand the checksum routine, and for other hints in general).<\/p>\n<p>It was rather pleasing to not only get this working but to make it work far better in terms of functionality and robustness, all the while reinforcing and extending my understanding of Python.<\/p>\n<p>Note: The original C source for &#8220;ping&#8221; can be found <a href=\"http:\/\/ping127001.com\/pingpage.htm\" target=\"_blank\">here<\/a> (you&#8217;ll need to extract it from ping.shar). Or just search for ping.c&#8230; for example, I found an identical copy of ping.c <a href=\"http:\/\/ws.edu.isoc.org\/materials\/src\/ping.c\" target=\"_blank\">here<\/a>.<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n#!\/usr\/bin\/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n&quot;&quot;&quot;\r\n    A pure python ping implementation using raw sockets.\r\n\r\n    (This is Python 3 port of https:\/\/github.com\/jedie\/python-ping)\r\n\r\n    Note that ICMP messages can only be sent from processes running as root\r\n    (in Windows, you must run this script as 'Administrator').\r\n\r\n    Derived from ping.c distributed in Linux's netkit. That code is\r\n    copyright (c) 1989 by The Regents of the University of California.\r\n    That code is in turn derived from code written by Mike Muuss of the\r\n    US Army Ballistic Research Laboratory in December, 1983 and\r\n    placed in the public domain. They have my thanks.\r\n\r\n    Bugs are naturally mine. I'd be glad to hear about them. There are\r\n    certainly word - size dependencies here.\r\n\r\n    Copyright (c) Matthew Dixon Cowles, &lt;http:\/\/www.visi.com\/~mdc\/&gt;.\r\n    Distributable under the terms of the GNU General Public License\r\n    version 2. Provided with no warranties of any sort.\r\n\r\n    Original Version from Matthew Dixon Cowles:\r\n      -&gt; ftp:\/\/ftp.visi.com\/users\/mdc\/ping.py\r\n\r\n    Rewrite by Jens Diemer:\r\n      -&gt; http:\/\/www.python-forum.de\/post-69122.html#69122\r\n\r\n    Rewrite by George Notaras:\r\n      -&gt; http:\/\/www.g-loaded.eu\/2009\/10\/30\/python-ping\/\r\n\r\n    Enhancements by Martin Falatic:\r\n      -&gt; https:\/\/www.falatic.com\/index.php\/39\/pinging-with-python\r\n\r\n    Revision history\r\n    ~~~~~~~~~~~~~~~~\r\n\r\n    October 12, 2011\r\n    --------------\r\n    Merged updates from the main project\r\n      -&gt; https:\/\/github.com\/jedie\/python-ping\r\n\r\n    September 12, 2011\r\n    --------------\r\n    Bugfixes + cleanup by Jens Diemer\r\n    Tested with Ubuntu + Windows 7\r\n\r\n    September 6, 2011\r\n    --------------\r\n    Cleanup by Martin Falatic. Restored lost comments and docs. Improved\r\n    functionality: constant time between pings, internal times consistently\r\n    use milliseconds. Clarified annotations (e.g., in the checksum routine).\r\n    Using unsigned data in IP &amp; ICMP header pack\/unpack unless otherwise\r\n    necessary. Signal handling. Ping-style output formatting and stats.\r\n\r\n    August 3, 2011\r\n    --------------\r\n    Ported to py3k by Zach Ware. Mostly done by 2to3; also minor changes to\r\n    deal with bytes vs. string changes (no more ord() in checksum() because\r\n    &gt;source_string&lt; is actually bytes, added .encode() to data in\r\n    send_one_ping()).  That's about it.\r\n\r\n    March 11, 2010\r\n    --------------\r\n    changes by Samuel Stauffer:\r\n    - replaced time.clock with default_timer which is set to\r\n      time.clock on windows and time.time on other systems.\r\n\r\n    November 8, 2009\r\n    ----------------\r\n    Improved compatibility with GNU\/Linux systems.\r\n\r\n    Fixes by:\r\n     * George Notaras -- http:\/\/www.g-loaded.eu\r\n    Reported by:\r\n     * Chris Hallman -- http:\/\/cdhallman.blogspot.com\r\n\r\n    Changes in this release:\r\n     - Re-use time.time() instead of time.clock(). The 2007 implementation\r\n       worked only under Microsoft Windows. Failed on GNU\/Linux.\r\n       time.clock() behaves differently under the two OSes&#x5B;1].\r\n\r\n    &#x5B;1] http:\/\/docs.python.org\/library\/time.html#time.clock\r\n\r\n    May 30, 2007\r\n    ------------\r\n    little rewrite by Jens Diemer:\r\n     -  change socket asterisk import to a normal import\r\n     -  replace time.time() with time.clock()\r\n     -  delete &quot;return None&quot; (or change to &quot;return&quot; only)\r\n     -  in checksum() rename &quot;str&quot; to &quot;source_string&quot;\r\n\r\n    December 4, 2000\r\n    ----------------\r\n    Changed the struct.pack() calls to pack the checksum and ID as\r\n    unsigned. My thanks to Jerome Poincheval for the fix.\r\n\r\n    November 22, 1997\r\n    -----------------\r\n    Initial hack. Doesn't do much, but rather than try to guess\r\n    what features I (or others) will want in the future, I've only\r\n    put in what I need now.\r\n\r\n    December 16, 1997\r\n    -----------------\r\n    For some reason, the checksum bytes are in the wrong order when\r\n    this is run under Solaris 2.X for SPARC but it works right under\r\n    Linux x86. Since I don't know just what's wrong, I'll swap the\r\n    bytes always and then do an htons().\r\n\r\n    ===========================================================================\r\n    IP header info from RFC791\r\n      -&gt; http:\/\/tools.ietf.org\/html\/rfc791)\r\n\r\n    0                   1                   2                   3\r\n    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\r\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n    |Version|  IHL  |Type of Service|          Total Length         |\r\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n    |         Identification        |Flags|      Fragment Offset    |\r\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n    |  Time to Live |    Protocol   |         Header Checksum       |\r\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n    |                       Source Address                          |\r\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n    |                    Destination Address                        |\r\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n    |                    Options                    |    Padding    |\r\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n\r\n    ===========================================================================\r\n    ICMP Echo \/ Echo Reply Message header info from RFC792\r\n      -&gt; http:\/\/tools.ietf.org\/html\/rfc792\r\n\r\n        0                   1                   2                   3\r\n        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\r\n        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n        |     Type      |     Code      |          Checksum             |\r\n        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n        |           Identifier          |        Sequence Number        |\r\n        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\r\n        |     Data ...\r\n        +-+-+-+-+-\r\n\r\n    ===========================================================================\r\n    ICMP parameter info:\r\n      -&gt; http:\/\/www.iana.org\/assignments\/icmp-parameters\/icmp-parameters.xml\r\n\r\n    ===========================================================================\r\n    An example of ping's typical output:\r\n\r\n    PING heise.de (193.99.144.80): 56 data bytes\r\n    64 bytes from 193.99.144.80: icmp_seq=0 ttl=240 time=127 ms\r\n    64 bytes from 193.99.144.80: icmp_seq=1 ttl=240 time=127 ms\r\n    64 bytes from 193.99.144.80: icmp_seq=2 ttl=240 time=126 ms\r\n    64 bytes from 193.99.144.80: icmp_seq=3 ttl=240 time=126 ms\r\n    64 bytes from 193.99.144.80: icmp_seq=4 ttl=240 time=127 ms\r\n\r\n    ----heise.de PING Statistics----\r\n    5 packets transmitted, 5 packets received, 0.0% packet loss\r\n    round-trip (ms)  min\/avg\/max\/med = 126\/127\/127\/127\r\n\r\n    ===========================================================================\r\n&quot;&quot;&quot;\r\n\r\n#=============================================================================#\r\nimport os, sys, socket, struct, select, time, signal\r\n\r\nif sys.platform == &quot;win32&quot;:\r\n    # On Windows, the best timer is time.clock()\r\n    default_timer = time.clock\r\nelse:\r\n    # On most other platforms the best timer is time.time()\r\n    default_timer = time.time\r\n\r\n#=============================================================================#\r\n# ICMP parameters\r\n\r\nICMP_ECHOREPLY  =    0 # Echo reply (per RFC792)\r\nICMP_ECHO       =    8 # Echo request (per RFC792)\r\nICMP_MAX_RECV   = 2048 # Max size of incoming buffer\r\n\r\nMAX_SLEEP = 1000\r\n\r\nclass MyStats:\r\n    thisIP   = &quot;0.0.0.0&quot;\r\n    pktsSent = 0\r\n    pktsRcvd = 0\r\n    minTime  = 999999999\r\n    maxTime  = 0\r\n    totTime  = 0\r\n    fracLoss = 1.0\r\n\r\nmyStats = MyStats # Used globally\r\n\r\n#=============================================================================#\r\ndef checksum(source_string):\r\n    &quot;&quot;&quot;\r\n    A port of the functionality of in_cksum() from ping.c\r\n    Ideally this would act on the string as a series of 16-bit ints (host\r\n    packed), but this works.\r\n    Network data is big-endian, hosts are typically little-endian\r\n    &quot;&quot;&quot;\r\n    countTo = (int(len(source_string)\/2))*2\r\n    sum = 0\r\n    count = 0\r\n\r\n    # Handle bytes in pairs (decoding as short ints)\r\n    loByte = 0\r\n    hiByte = 0\r\n    while count &lt; countTo:\r\n        if (sys.byteorder == &quot;little&quot;):\r\n            loByte = source_string&#x5B;count]\r\n            hiByte = source_string&#x5B;count + 1]\r\n        else:\r\n            loByte = source_string&#x5B;count + 1]\r\n            hiByte = source_string&#x5B;count]\r\n        sum = sum + (hiByte * 256 + loByte)\r\n        count += 2\r\n\r\n    # Handle last byte if applicable (odd-number of bytes)\r\n    # Endianness should be irrelevant in this case\r\n    if countTo &lt; len(source_string): # Check for odd length\r\n        loByte = source_string&#x5B;len(source_string)-1]\r\n        sum += loByte\r\n\r\n    sum &amp;= 0xffffffff # Truncate sum to 32 bits (a variance from ping.c, which\r\n                      # uses signed ints, but overflow is unlikely in ping)\r\n\r\n    sum = (sum &gt;&gt; 16) + (sum &amp; 0xffff)    # Add high 16 bits to low 16 bits\r\n    sum += (sum &gt;&gt; 16)                    # Add carry from above (if any)\r\n    answer = ~sum &amp; 0xffff              # Invert and truncate to 16 bits\r\n    answer = socket.htons(answer)\r\n\r\n    return answer\r\n\r\n#=============================================================================#\r\ndef do_one(destIP, timeout, mySeqNumber, numDataBytes):\r\n    &quot;&quot;&quot;\r\n    Returns either the delay (in ms) or None on timeout.\r\n    &quot;&quot;&quot;\r\n    global myStats\r\n\r\n    delay = None\r\n\r\n    try: # One could use UDP here, but it's obscure\r\n        mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname(&quot;icmp&quot;))\r\n    except socket.error as e:\r\n        print(&quot;failed. (socket error: '%s')&quot; % e.args&#x5B;1])\r\n        raise # raise the original error\r\n\r\n    my_ID = os.getpid() &amp; 0xFFFF\r\n\r\n    sentTime = send_one_ping(mySocket, destIP, my_ID, mySeqNumber, numDataBytes)\r\n    if sentTime == None:\r\n        mySocket.close()\r\n        return delay\r\n\r\n    myStats.pktsSent += 1;\r\n\r\n    recvTime, dataSize, iphSrcIP, icmpSeqNumber, iphTTL = receive_one_ping(mySocket, my_ID, timeout)\r\n\r\n    mySocket.close()\r\n\r\n    if recvTime:\r\n        delay = (recvTime-sentTime)*1000\r\n        print(&quot;%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms&quot; % (\r\n            dataSize, socket.inet_ntoa(struct.pack(&quot;!I&quot;, iphSrcIP)), icmpSeqNumber, iphTTL, delay)\r\n        )\r\n        myStats.pktsRcvd += 1;\r\n        myStats.totTime += delay\r\n        if myStats.minTime &gt; delay:\r\n            myStats.minTime = delay\r\n        if myStats.maxTime &lt; delay:\r\n            myStats.maxTime = delay\r\n    else:\r\n        delay = None\r\n        print(&quot;Request timed out.&quot;)\r\n\r\n    return delay\r\n\r\n#=============================================================================#\r\ndef send_one_ping(mySocket, destIP, myID, mySeqNumber, numDataBytes):\r\n    &quot;&quot;&quot;\r\n    Send one ping to the given &gt;destIP&lt;.\r\n    &quot;&quot;&quot;\r\n    destIP  =  socket.gethostbyname(destIP)\r\n\r\n    # Header is type (8), code (8), checksum (16), id (16), sequence (16)\r\n    myChecksum = 0\r\n\r\n    # Make a dummy heder with a 0 checksum.\r\n    header = struct.pack(\r\n        &quot;!BBHHH&quot;, ICMP_ECHO, 0, myChecksum, myID, mySeqNumber\r\n    )\r\n\r\n    padBytes = &#x5B;]\r\n    startVal = 0x42\r\n    for i in range(startVal, startVal + (numDataBytes)):\r\n        padBytes += &#x5B;(i &amp; 0xff)]  # Keep chars in the 0-255 range\r\n    data = bytes(padBytes)\r\n\r\n    # Calculate the checksum on the data and the dummy header.\r\n    myChecksum = checksum(header + data) # Checksum is in network order\r\n\r\n    # Now that we have the right checksum, we put that in. It's just easier\r\n    # to make up a new header than to stuff it into the dummy.\r\n    header = struct.pack(\r\n        &quot;!BBHHH&quot;, ICMP_ECHO, 0, myChecksum, myID, mySeqNumber\r\n    )\r\n\r\n    packet = header + data\r\n\r\n    sendTime = time.time()\r\n\r\n    try:\r\n        mySocket.sendto(packet, (destIP, 1)) # Port number is irrelevant for ICMP\r\n    except socket.error as e:\r\n        print(&quot;General failure (%s)&quot; % (e.args&#x5B;1]))\r\n        return\r\n\r\n    return sendTime\r\n\r\n#=============================================================================#\r\ndef receive_one_ping(mySocket, myID, timeout):\r\n    &quot;&quot;&quot;\r\n    Receive the ping from the socket. Timeout = in ms\r\n    &quot;&quot;&quot;\r\n    timeLeft = timeout\/1000\r\n\r\n    while True: # Loop while waiting for packet or timeout\r\n        startedSelect = time.time()\r\n        whatReady = select.select(&#x5B;mySocket], &#x5B;], &#x5B;], timeLeft)\r\n        howLongInSelect = (time.time() - startedSelect)\r\n        if whatReady&#x5B;0] == &#x5B;]: # Timeout\r\n            return None, 0, 0, 0, 0\r\n\r\n        timeReceived = time.time()\r\n\r\n        recPacket, addr = mySocket.recvfrom(ICMP_MAX_RECV)\r\n\r\n        ipHeader = recPacket&#x5B;:20]\r\n        iphVersion, iphTypeOfSvc, iphLength, \\\r\n        iphID, iphFlags, iphTTL, iphProtocol, \\\r\n        iphChecksum, iphSrcIP, iphDestIP = struct.unpack(\r\n            &quot;!BBHHHBBHII&quot;, ipHeader\r\n        )\r\n\r\n        icmpHeader = recPacket&#x5B;20:28]\r\n        icmpType, icmpCode, icmpChecksum, \\\r\n        icmpPacketID, icmpSeqNumber = struct.unpack(\r\n            &quot;!BBHHH&quot;, icmpHeader\r\n        )\r\n\r\n        if icmpPacketID == myID: # Our packet\r\n            dataSize = len(recPacket) - 28\r\n            return timeReceived, dataSize, iphSrcIP, icmpSeqNumber, iphTTL\r\n\r\n        timeLeft = timeLeft - howLongInSelect\r\n        if timeLeft &lt;= 0:\r\n            return None, 0, 0, 0, 0\r\n\r\n#=============================================================================#\r\ndef dump_stats():\r\n    &quot;&quot;&quot;\r\n    Show stats when pings are done\r\n    &quot;&quot;&quot;\r\n    global myStats\r\n\r\n    print(&quot;\\n----%s PYTHON PING Statistics----&quot; % (myStats.thisIP))\r\n\r\n    if myStats.pktsSent &gt; 0:\r\n        myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd)\/myStats.pktsSent\r\n\r\n    print(&quot;%d packets transmitted, %d packets received, %0.1f%% packet loss&quot; % (\r\n        myStats.pktsSent, myStats.pktsRcvd, 100.0 * myStats.fracLoss\r\n    ))\r\n\r\n    if myStats.pktsRcvd &gt; 0:\r\n        print(&quot;round-trip (ms)  min\/avg\/max = %d\/%0.1f\/%d&quot; % (\r\n            myStats.minTime, myStats.totTime\/myStats.pktsRcvd, myStats.maxTime\r\n        ))\r\n\r\n    print()\r\n    return\r\n\r\n#=============================================================================#\r\ndef signal_handler(signum, frame):\r\n    &quot;&quot;&quot;\r\n    Handle exit via signals\r\n    &quot;&quot;&quot;\r\n    dump_stats()\r\n    print(&quot;\\n(Terminated with signal %d)\\n&quot; % (signum))\r\n    sys.exit(0)\r\n\r\n#=============================================================================#\r\ndef verbose_ping(hostname, timeout = 1000, count = 3, numDataBytes = 55):\r\n    &quot;&quot;&quot;\r\n    Send &gt;count&lt; ping to &gt;destIP&lt; with the given &gt;timeout&lt; and display\r\n    the result.\r\n    &quot;&quot;&quot;\r\n    global myStats\r\n\r\n    signal.signal(signal.SIGINT, signal_handler)   # Handle Ctrl-C\r\n    if hasattr(signal, &quot;SIGBREAK&quot;):\r\n        # Handle Ctrl-Break e.g. under Windows\r\n        signal.signal(signal.SIGBREAK, signal_handler)\r\n\r\n    myStats = MyStats() # Reset the stats\r\n\r\n    mySeqNumber = 0 # Starting value\r\n\r\n    try:\r\n        destIP = socket.gethostbyname(hostname)\r\n        print(&quot;\\nPYTHON PING %s (%s): %d data bytes&quot; % (hostname, destIP, numDataBytes))\r\n    except socket.gaierror as e:\r\n        print(&quot;\\nPYTHON PING: Unknown host: %s (%s)&quot; % (hostname, e.args&#x5B;1]))\r\n        print()\r\n        return\r\n\r\n    myStats.thisIP = destIP\r\n\r\n    for i in range(count):\r\n        delay = do_one(destIP, timeout, mySeqNumber, numDataBytes)\r\n\r\n        if delay == None:\r\n            delay = 0\r\n\r\n        mySeqNumber += 1\r\n\r\n        # Pause for the remainder of the MAX_SLEEP period (if applicable)\r\n        if (MAX_SLEEP &gt; delay):\r\n            time.sleep((MAX_SLEEP - delay)\/1000)\r\n\r\n    dump_stats()\r\n\r\n#=============================================================================#\r\nif __name__ == '__main__':\r\n\r\n    # These should work:\r\n    verbose_ping(&quot;heise.de&quot;)\r\n    verbose_ping(&quot;google.com&quot;)\r\n\r\n    # Inconsistent on Windows w\/ ActivePython (Python 3.2 resolves correctly\r\n    # to the local host, but 2.7 tries to resolve to the local *gateway*)\r\n    verbose_ping(&quot;localhost&quot;)\r\n\r\n    # Should fail with 'getaddrinfo failed':\r\n    verbose_ping(&quot;foobar_url.foobar&quot;)\r\n\r\n    # Should fail (timeout), but it depends on the local network:\r\n    verbose_ping(&quot;192.168.255.254&quot;)\r\n\r\n    # Should fails with 'The requested address is not valid in its context':\r\n    verbose_ping(&quot;0.0.0.0&quot;)\r\n\r\n#=============================================================================#\r\n\r\n<\/pre>\n<!-- wpsso rrssb get buttons: buttons on archive option not enabled -->\n","protected":false},"excerpt":{"rendered":"<p>2015-05-28 update: Some of the old repos mentioned in this article are gone. You can check out Georgi Kolev&#8217;s repo (which has been recently updated) or my older one. Jens <a href=\"https:\/\/www.falatic.com\/index.php\/39\/pinging-with-python\" class=\"more-link\">[&hellip;]<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"Layout":"","footnotes":"","_links_to":"","_links_to_target":""},"categories":[86,1],"tags":[31,68,69,67,66,70,117],"class_list":["entry","author-marty","has-more-link","post-39","post","type-post","status-publish","format-standard","category-software-and-hardware-development","category-uncategorized","tag-cygwin","tag-icmp","tag-ip","tag-ping","tag-python-3","tag-unix","tag-windows"],"_links":{"self":[{"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/posts\/39","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/comments?post=39"}],"version-history":[{"count":0,"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/posts\/39\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/media?parent=39"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/categories?post=39"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.falatic.com\/index.php\/wp-json\/wp\/v2\/tags?post=39"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}