python实现ping的方法


Posted in Python onJuly 06, 2015

本文实例讲述了python实现ping的方法。分享给大家供大家参考。具体如下:

#!/usr/bin/env python
#coding:utf-8
import os, sys, socket, struct, select, time
# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.
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
  """
  sum = 0
  countTo = (len(source_string)/2)*2
  count = 0
  while count<countTo:
    thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
    sum = sum + thisVal
    sum = sum & 0xffffffff # Necessary?
    count = count + 2
  if countTo<len(source_string):
    sum = sum + ord(source_string[len(source_string) - 1])
    sum = sum & 0xffffffff # Necessary?
  sum = (sum >> 16) + (sum & 0xffff)
  sum = sum + (sum >> 16)
  answer = ~sum
  answer = answer & 0xffff
  # Swap bytes. Bugger me if I know why.
  answer = answer >> 8 | (answer << 8 & 0xff00)
  return answer
def receive_one_ping(my_socket, ID, timeout):
  """
  receive the ping from the socket.
  """
  timeLeft = timeout
  while True:
    startedSelect = time.time()
    whatReady = select.select([my_socket], [], [], timeLeft)
    howLongInSelect = (time.time() - startedSelect)
    if whatReady[0] == []: # Timeout
      return
    timeReceived = time.time()
    recPacket, addr = my_socket.recvfrom(1024)
    icmpHeader = recPacket[20:28]
    type, 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
def send_one_ping(my_socket, dest_addr, ID):
  """
  Send one ping to the given >dest_addr<.
  """
  dest_addr = socket.gethostbyname(dest_addr)
  # Header is type (8), code (8), checksum (16), id (16), sequence (16)
  my_checksum = 0
  # Make a dummy heder with a 0 checksum.
  header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) #压包
  #a1 = struct.unpack("bbHHh",header)  #my test
  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.
  my_checksum = 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.
  header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1)
  packet = header + data
  my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(dest_addr, timeout):
  """
  Returns either the delay (in seconds) or none on timeout.
  """
  icmp = socket.getprotobyname("icmp")
  try:
    my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
  except socket.error, (errno, msg):
    if errno == 1:
      # Operation not permitted
      msg = msg + (
        " - Note that ICMP messages can only be sent from processes"
        " running as root."
      )
      raise socket.error(msg)
    raise # raise the original error
  my_ID = os.getpid() & 0xFFFF
  send_one_ping(my_socket, dest_addr, my_ID)
  delay = receive_one_ping(my_socket, my_ID, timeout)
  my_socket.close()
  return delay
def verbose_ping(dest_addr, timeout = 2, count = 100):
  """
  Send >count< ping to >dest_addr< with the given >timeout< and display
  the result.
  """
  for i in xrange(count):
    print "ping %s..." % dest_addr,
    try:
      delay = do_one(dest_addr, timeout)
    except socket.gaierror, e:
      print "failed. (socket error: '%s')" % e[1]
      break
    if delay == None:
      print "failed. (timeout within %ssec.)" % timeout
    else:
      delay = delay * 1000
      print "get ping in %0.4fms" % delay
if __name__ == '__main__':
  verbose_ping("www.163.com",2,1)

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
Python入门之modf()方法的使用
May 15 Python
Python中字符串的修改及传参详解
Nov 30 Python
python函数的5种参数详解
Feb 24 Python
python爬虫入门教程--HTML文本的解析库BeautifulSoup(四)
May 25 Python
Python实现复杂对象转JSON的方法示例
Jun 22 Python
OPENCV去除小连通区域,去除孔洞的实例讲解
Jun 21 Python
python处理两种分隔符的数据集方法
Dec 12 Python
python批量读取文件名并写入txt文件中
Sep 05 Python
Pytorch 多维数组运算过程的索引处理方式
Dec 27 Python
使用OpenCV对车道进行实时检测的实现示例代码
Jun 19 Python
Python Opencv实现单目标检测的示例代码
Sep 08 Python
python接口测试返回数据为字典取值方式
Feb 12 Python
python删除指定类型(或非指定)的文件实例详解
Jul 06 #Python
python根据日期返回星期几的方法
Jul 06 #Python
python获取文件扩展名的方法
Jul 06 #Python
python创建临时文件夹的方法
Jul 06 #Python
Python中几个比较常见的名词解释
Jul 04 #Python
python检测是文件还是目录的方法
Jul 03 #Python
python生成随机密码或随机字符串的方法
Jul 03 #Python
You might like
在项目中寻找代码的坏命名
2012/07/14 PHP
解析PHP将对象转换成数组的方法(兼容多维数组类型)
2013/06/21 PHP
PHP的构造方法,析构方法和this关键字详细介绍
2013/10/22 PHP
PHP标准库(PHP SPL)详解
2019/03/16 PHP
使用Modello编写JavaScript类
2006/12/22 Javascript
JavaScript mapreduce工作原理简析
2012/11/25 Javascript
ExtJS4 表格的嵌套 rowExpander应用
2014/05/02 Javascript
js获取指定日期周数以及星期几的小例子
2014/06/27 Javascript
js的image onload事件使用遇到的问题
2014/07/15 Javascript
10分钟学会写Jquery插件实例教程
2014/09/06 Javascript
运用jQuery定时器的原理实现banner图片切换
2014/10/22 Javascript
jQuery文字提示与图片提示效果实现方法
2016/07/04 Javascript
javascript实现文字无缝滚动
2016/12/27 Javascript
js实现文字无缝向上滚动
2017/02/16 Javascript
Java中int与integer的区别(基本数据类型与引用数据类型)
2017/02/19 Javascript
Cookies 和 Session的详解及区别
2017/04/21 Javascript
分分钟学会vue中vuex的应用(入门教程)
2017/09/14 Javascript
如何解决vue2.0下IE浏览器白屏问题
2018/09/13 Javascript
vue在index.html中引入静态文件不生效问题及解决方法
2019/04/29 Javascript
原生js实现瀑布流效果
2020/03/09 Javascript
Python中的异常处理相关语句基础学习笔记
2016/07/11 Python
OpenCV-Python实现轮廓检测实例分析
2018/01/05 Python
详细解读tornado协程(coroutine)原理
2018/01/15 Python
对django中render()与render_to_response()的区别详解
2018/10/16 Python
详解如何设置Python环境变量?
2019/05/13 Python
Python实现动态循环输出文字功能
2020/05/07 Python
Python定时任务APScheduler原理及实例解析
2020/05/30 Python
关于Python 解决Python3.9 pandas.read_excel(‘xxx.xlsx‘)报错的问题
2020/11/28 Python
网游商务专员求职信
2013/10/15 职场文书
中文专业毕业生自荐书范文
2014/01/04 职场文书
企业党员公开承诺书
2014/03/26 职场文书
先进个人总结范文
2015/02/15 职场文书
运动与健康自我评价
2015/03/09 职场文书
2015年食堂工作总结报告
2015/04/23 职场文书
爱的教育观后感
2015/06/17 职场文书
Python Django项目和应用的创建详解
2021/11/27 Python