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网络爬虫项目:内容提取器的定义
Oct 25 Python
Python实现判断给定列表是否有重复元素的方法
Apr 11 Python
PyQt5每天必学之像素图控件QPixmap
Apr 19 Python
python中in在list和dict中查找效率的对比分析
May 04 Python
Python读写zip压缩文件的方法
Aug 29 Python
Python实现的微信支付方式总结【三种方式】
Apr 13 Python
python多继承(钻石继承)问题和解决方法简单示例
Oct 21 Python
python判断无向图环是否存在的示例
Nov 22 Python
python设置环境变量的作用整理
Feb 17 Python
Python xlrd模块导入过程及常用操作
Jun 10 Python
python上下文管理器异常问题解决方法
Feb 07 Python
python - asyncio异步编程
Apr 06 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
PHP 的ArrayAccess接口 像数组一样来访问你的PHP对象
2010/10/12 PHP
PHP中使用smarty生成静态文件的例子
2014/04/24 PHP
php实现的click captcha点击验证码类实例
2014/09/23 PHP
完美实现wordpress禁止文章修订和自动保存的方法
2014/11/03 PHP
WordPress中设置Post Type自定义文章类型的实例教程
2016/05/10 PHP
Yii框架自定义数据库操作组件示例
2019/11/11 PHP
javascript hasFocus使用实例
2010/06/29 Javascript
javascript图像处理—仿射变换深度理解
2013/01/16 Javascript
复选框全选与全不选操作实现思路
2013/08/18 Javascript
js单例模式的两种方案
2013/10/22 Javascript
JavaScript获得指定对象大小的方法
2015/07/01 Javascript
javascript中mouseover、mouseout使用详解
2015/07/19 Javascript
node.js插件nodeclipse安装图文教程
2020/10/19 Javascript
nodeJS删除文件方法示例
2016/12/25 NodeJs
jQuery的中 is(':visible') 解析及用法(必看)
2017/02/12 Javascript
Angularjs 动态添加指令并绑定事件的方法
2017/04/13 Javascript
jQuery异步提交表单实例
2017/05/30 jQuery
Linux系统中利用node.js提取Word(doc/docx)及PDF文本的内容
2017/06/17 Javascript
浅谈Vue.js应用的四种AJAX请求数据模式
2017/08/30 Javascript
详解如何在react中搭建d3力导向图
2018/01/12 Javascript
vue-router 路由传参用法实例分析
2020/03/06 Javascript
[02:41]《西雅图我们来了》2015国际邀请赛出征全记录
2015/07/23 DOTA
基于Python 的进程管理工具supervisor使用指南
2016/09/18 Python
windows10下python3.5 pip3安装图文教程
2018/04/02 Python
python写入已存在的excel数据实例
2018/05/03 Python
对tf.reduce_sum tensorflow维度上的操作详解
2018/07/26 Python
python安装本地whl的实例步骤
2019/10/12 Python
python 服务器运行代码报错ModuleNotFoundError的解决办法
2020/09/16 Python
JupyterNotebook 输出窗口的显示效果调整实现
2020/09/22 Python
加拿大廉价机票预订网站:CheapOair.ca
2018/03/04 全球购物
会计实习自我鉴定
2013/12/04 职场文书
餐厅总厨求职信
2014/03/04 职场文书
小学六年级学生评语
2014/04/22 职场文书
2014年出纳工作总结与计划
2014/12/09 职场文书
前台接待岗位职责范本
2015/04/03 职场文书
分家协议书范本
2016/03/22 职场文书