473,698 Members | 2,452 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to ping in Python?

Hi there,

I could not find any "ping" Class or Handler in python (2.3.5) to ping a
machine.
I just need to "ping" a machine to see if its answering. What's the best
way to do it?

Kind regards,
Nico
Dec 5 '05 #1
8 18388
Try the PyNMS libraries:
http://freshmeat.net/projects/pynms/

It has a ping module. If all you need is the ping module, maybe you
could just look through that code and see if it's relatively simple to
impliment yourself.

Dec 5 '05 #2
Nico Grubert wrote:
Hi there,

I could not find any "ping" Class or Handler in python (2.3.5) to ping a
machine.
I just need to "ping" a machine to see if its answering. What's the best
way to do it?

Kind regards,
Nico

# 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.

# Note that ICMP messages can only be sent from processes running
# as root.

# 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.
#

# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUE ST = 8 # Seems to be the same on Solaris.

# 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
def checksum(str):
csum = 0
countTo = (len(str) / 2) * 2
count = 0
while count < countTo:
thisVal = ord(str[count+1]) * 256 + ord(str[count])
csum = csum + thisVal
csum = csum & 0xffffffffL # Necessary?
count = count + 2

if countTo < len(str):
csum = csum + ord(str[len(str) - 1])
csum = csum & 0xffffffffL # Necessary?

csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff

# Swap bytes. Bugger me if I know why.
answer = answer >> 8 | (answer << 8 & 0xff00)

return answer

def receiveOnePing( mySocket, ID, timeout):
timeLeft = timeout

while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)

if whatReady[0] == []: # Timeout
return -1

timeReceived = time.time()
recPacket, addr = mySocket.recvfr om(1024)
icmpHeader = recPacket[20:28]
typ, code, checksum, packetID, sequence =
struct.unpack(" bbHHh", icmpHeader)

if packetID == ID:
bytesInDouble = struct.calcsize ("d")
timeSent = struct.unpack(" d", recPacket[28:28 +
bytesInDouble])[0]
return timeReceived - timeSent

timeLeft = timeLeft - howLongInSelect

if timeLeft <= 0:
return -1

def sendOnePing(myS ocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0

# Make a dummy heder with a 0 checksum.
header = struct.pack("bb HHh", ICMP_ECHO_REQUE ST, 0, myChecksum, ID, 1)
bytesInDouble = struct.calcsize ("d")
data = (192 - bytesInDouble) * "Q"
data = struct.pack("d" , time.time()) + data

# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)

# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy.
if prop.platform == 'darwin':
myChecksum = socket.htons(my Checksum) & 0xffff
else:
myChecksum = socket.htons(my Checksum)

header = struct.pack("bb HHh", ICMP_ECHO_REQUE ST, 0,
myChecksum, ID, 1)

packet = header + data
mySocket.sendto (packet, (destAddr, 1)) # Don't know about the 1

def doOne(destAddr, timeout=10):
# Returns either the delay (in seconds) or none on timeout.
icmp = socket.getproto byname("icmp")
mySocket = socket.socket(s ocket.AF_INET,s ocket.SOCK_RAW, icmp)
myID = os.getpid() & 0xFFFF
sendOnePing(myS ocket, destAddr, myID)
delay = receiveOnePing( mySocket, myID, timeout)
mySocket.close( )

return delay
def ping(host, timeout=1):
dest = socket.gethostb yname(host)
delay = doOne(dest, timeout)
return delay

Dec 5 '05 #3
Seems that you must change the following lines to work:

if prop.platform == 'darwin':
myChecksum = socket.htons(my Checksum) & 0xffff
else:
myChecksum = socket.htons(my Checksum)

to

if sys.platform == 'darwin':
myChecksum = socket.htons(my Checksum) & 0xffff
else:
myChecksum = socket.htons(my Checksum)

You also must import the following modules:

import socket
import os
import sys
import struct
import time
import select

-Larry Bates

dwelch wrote:
Nico Grubert wrote:
Hi there,

I could not find any "ping" Class or Handler in python (2.3.5) to ping
a machine.
I just need to "ping" a machine to see if its answering. What's the
best way to do it?

Kind regards,
Nico


# 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.

# Note that ICMP messages can only be sent from processes running
# as root.

# 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.
#

# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUE ST = 8 # Seems to be the same on Solaris.

# 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
def checksum(str):
csum = 0
countTo = (len(str) / 2) * 2
count = 0
while count < countTo:
thisVal = ord(str[count+1]) * 256 + ord(str[count])
csum = csum + thisVal
csum = csum & 0xffffffffL # Necessary?
count = count + 2

if countTo < len(str):
csum = csum + ord(str[len(str) - 1])
csum = csum & 0xffffffffL # Necessary?

csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff

# Swap bytes. Bugger me if I know why.
answer = answer >> 8 | (answer << 8 & 0xff00)

return answer

def receiveOnePing( mySocket, ID, timeout):
timeLeft = timeout

while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)

if whatReady[0] == []: # Timeout
return -1

timeReceived = time.time()
recPacket, addr = mySocket.recvfr om(1024)
icmpHeader = recPacket[20:28]
typ, code, checksum, packetID, sequence = struct.unpack(" bbHHh",
icmpHeader)

if packetID == ID:
bytesInDouble = struct.calcsize ("d")
timeSent = struct.unpack(" d", recPacket[28:28 +
bytesInDouble])[0]
return timeReceived - timeSent

timeLeft = timeLeft - howLongInSelect

if timeLeft <= 0:
return -1

def sendOnePing(myS ocket, destAddr, ID):
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0

# Make a dummy heder with a 0 checksum.
header = struct.pack("bb HHh", ICMP_ECHO_REQUE ST, 0, myChecksum, ID, 1)
bytesInDouble = struct.calcsize ("d")
data = (192 - bytesInDouble) * "Q"
data = struct.pack("d" , time.time()) + data

# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(header + data)

# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy.
if prop.platform == 'darwin':
myChecksum = socket.htons(my Checksum) & 0xffff
else:
myChecksum = socket.htons(my Checksum)

header = struct.pack("bb HHh", ICMP_ECHO_REQUE ST, 0,
myChecksum, ID, 1)

packet = header + data
mySocket.sendto (packet, (destAddr, 1)) # Don't know about the 1

def doOne(destAddr, timeout=10):
# Returns either the delay (in seconds) or none on timeout.
icmp = socket.getproto byname("icmp")
mySocket = socket.socket(s ocket.AF_INET,s ocket.SOCK_RAW, icmp)
myID = os.getpid() & 0xFFFF
sendOnePing(myS ocket, destAddr, myID)
delay = receiveOnePing( mySocket, myID, timeout)
mySocket.close( )

return delay
def ping(host, timeout=1):
dest = socket.gethostb yname(host)
delay = doOne(dest, timeout)
return delay

Dec 5 '05 #4
I telnet to port 13 (returns time)

Hope this is helpful,
Mike

Nico Grubert wrote:
Hi there,

I could not find any "ping" Class or Handler in python (2.3.5) to ping a
machine.
I just need to "ping" a machine to see if its answering. What's the best
way to do it?

Kind regards,
Nico

--
The greatest performance improvement occurs on the transition of from
the non-working state to the working state.
Dec 7 '05 #5
I telnet to port 13 (returns time)

Hope this is helpful,
Mike

Nico Grubert wrote:
Hi there,

I could not find any "ping" Class or Handler in python (2.3.5) to ping a
machine.
I just need to "ping" a machine to see if its answering. What's the best
way to do it?

Kind regards,
Nico

--
The greatest performance improvement occurs on the transition of from
the non-working state to the working state.
Dec 7 '05 #6
Michael Schneider wrote:
I telnet to port 13 (returns time)

The problem is that most modern up-to-date servers use firewalls. They
only open the ports that are absolutely necessary. Usually the time
service is part of inetd, which is disabled by default, on most of the
servers. PING ICMP may work, but sometimes it does not either. In the
worst case, all port are closed and you have no way to tell if there is
a computer or not.

Can you tell more about what kind of server do you need to "ping"?

Example: if you need to know if a web server is alive, you should
connect to port 80 (http). If the connection was successful, you can
close the connection immeditelly. You can expect a HTTP server to open
the HTTP port, but all other ports may be closed.

Les

Dec 7 '05 #7
Les,

I only ping internal machines. You are right about shutting down ports.

When we disable telent, we also disable ping. Many people may not though,

good luck,
Mike

Laszlo Zsolt Nagy wrote:
Michael Schneider wrote:
I telnet to port 13 (returns time)

The problem is that most modern up-to-date servers use firewalls. They
only open the ports that are absolutely necessary. Usually the time
service is part of inetd, which is disabled by default, on most of the
servers. PING ICMP may work, but sometimes it does not either. In the
worst case, all port are closed and you have no way to tell if there
is a computer or not.

Can you tell more about what kind of server do you need to "ping"?

Example: if you need to know if a web server is alive, you should
connect to port 80 (http). If the connection was successful, you can
close the connection immeditelly. You can expect a HTTP server to open
the HTTP port, but all other ports may be closed.

Les

--
The greatest performance improvement occurs on the transition of from the non-working state to the working state.

Dec 7 '05 #8
Nico Grubert enlightened us with:
I just need to "ping" a machine to see if its answering. What's the
best way to do it?


To do a real ICMP ping, you need raw sockets, which are turned off on
Windows and reserved for root on other systems. You could try to
connect to an unused port, and see how fast a RST packet is returned.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Dec 7 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8402
by: Sean Cody | last post by:
Does anyone know of an ping module that will work with Windows? I'm currently using os.popen("ping -n1 host") but it's terribly slow when using it a few hundred times. After enumerating my domain of machines I'm trying to ping them to determine if they are active before connecting to them via WMI (which takes forever to timeout). --
2
5367
by: Alberto Vera | last post by:
Hello: Is it possible to make "ping" from Python and get statistics like using command prompt from Windows? How Can I capture them into variables? Thanks Pinging XXXX.XXXX.XXXX.XXXX with 32 bytes of data:
2
2991
by: Count László de Almásy | last post by:
Greetings, I'm in need of a simple GUI application that "monitors" a range of hosts using ping and reports on their status by changing the panel color for that host (i.e, green for pingable, red for unreachable). Does anyone know of any existing opensource program that does this? Preferably Python so I can extend it easily. If not, what tools would you recommend I write this kind of app in?
3
1834
by: amaccormack | last post by:
I wrote a quick script to check the "up-ness" of a list of machines, and timeout after 1 second. However, with a lot of timeouts, the script takes a logn time, so I thought to parallelise it. However, as soon as I do, the pings that do not get a response never return, so their threads block forever and the program hangs. Environment is: Python 2.3.3 (#1, Jan 5 2005, 15:24:27) on linux2 (running on SLES9) pinglist=
7
6539
by: Linus Cohen | last post by:
Hi all, I'm a newbie to python and programming in general, so I wanted a simple project to start off. What I'm trying to do here is write a python command-line ping program, much like the Unix and Windows ping programs. I've got this much worked out already: class ping def PING(IP, pings, size): and that's where I stop, because I realize I have no idea how to make
5
2190
by: Mrown | last post by:
Hi, I was wondering if there was a ping implementation written in Python. I'd rather using a Python module that implements ping in a platform/OS-independent way than rely on the underlying OS, especially as every OS has a different implementation. Furthermore, if you're going to ping a large number of IPs, using a module would probably be a lot faster. Any ideas if such a module exists? Thanks.
1
2718
by: Mauro \Baba\ Mascia | last post by:
Hi, this is my question: I want to know if several switch (about 50) in a big lan are up and then know their MAC addresses to do a list that contains host name, ip and mac. I know only the range of their IP addresses (the host name it's simply to know using socket.gethostn. The first idea it's to ping all ip, parse the response and then execute the command "arp -a" and parse the response. However this way depends on the operating...
1
1822
by: Karl Kobata | last post by:
Hi Fredrik, This is exactly what I need. Thank you. I would like to do one additional function. I am not using the tokenizer to parse python code. It happens to work very well for my application. However, I would like either or both of the following variance: 1) I would like to add 2 other characters as comment designation 2) write a module that can readline, modify the line as required, and finally, this module can be used as the...
1
72545
by: ScottZ | last post by:
With python 2.6 and wxpython I'm trying to create a system tray icon application based around an example found here: http://codeboje.de/MailSneaker-Part-3-SystemTrayTaskBar-Icons-with-Python-and-wxPython/ The application will simply change the systray icon based on if an ip address is online or not. The ping portion looks like this: if os.name == "nt": # Windows
0
8678
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9166
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9030
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4371
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.