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 相关文章推荐
Pycharm远程调试openstack的方法
Nov 21 Python
python语言中with as的用法使用详解
Feb 23 Python
解决pandas无法在pycharm中使用plot()方法显示图像的问题
May 24 Python
wxPython的安装与使用教程
Aug 31 Python
Python3中lambda表达式与函数式编程讲解
Jan 14 Python
浅谈Python反射 &amp; 单例模式
Mar 21 Python
详解PyCharm安装MicroPython插件的教程
Jun 24 Python
解决python 读取excel时 日期变成数字并加.0的问题
Oct 08 Python
使用pyqt 实现重复打开多个相同界面
Dec 13 Python
Django接收照片储存文件的实例代码
Mar 07 Python
Python爬虫爬取、解析数据操作示例
Mar 27 Python
Python+MySQL随机试卷及答案生成程序的示例代码
Feb 01 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
WinXP + Apache +PHP5 + MySQL + phpMyAdmin安装全功略
2006/07/09 PHP
php魔术方法与魔术变量、内置方法与内置变量的深入分析
2013/06/03 PHP
PHP中的魔术方法总结和使用实例
2015/05/11 PHP
php删除二维数组中的重复值方法
2018/03/12 PHP
PHP7 mongoDB扩展使用的方法分享
2019/05/02 PHP
js网页侧边随页面滚动广告效果实现
2011/04/14 Javascript
屏蔽IE弹出&quot;您查看的网页正在试图关闭窗口,是否关闭此窗口&quot;的方法
2013/12/31 Javascript
详谈JavaScript内存泄漏
2014/11/14 Javascript
轻松创建nodejs服务器(2):nodejs服务器的构成分析
2014/12/18 NodeJs
浅谈JavaScript中指针和地址
2015/07/26 Javascript
js实现prototype扩展的方法(字符串,日期,数组扩展)
2016/01/14 Javascript
JavaScript设计模式经典之工厂模式
2016/02/24 Javascript
webpack+vue.js快速入门教程
2016/10/12 Javascript
微信小程序 教程之模板
2016/10/18 Javascript
JS实现数组按升序及降序排列的方法
2017/04/26 Javascript
通过jquery获取上传文件名称、类型和大小的实现代码
2018/04/19 jQuery
JavaScript树的深度优先遍历和广度优先遍历算法示例
2018/07/30 Javascript
vue实现点击隐藏与显示实例分享
2019/02/13 Javascript
Vue实现日历小插件
2019/06/26 Javascript
9种方法优化jQuery代码详解
2020/02/04 jQuery
[02:32]【DOTA2亚洲邀请赛】iceice,梦开始的地方
2017/03/13 DOTA
python获取当前时间对应unix时间戳的方法
2015/05/15 Python
解析Python编程中的包结构
2015/10/25 Python
利用python程序帮大家清理windows垃圾
2017/01/15 Python
Python 动态导入对象,importlib.import_module()的使用方法
2019/08/28 Python
最简单的matplotlib安装教程(小白)
2020/07/28 Python
当我正在为表建立索引的时候,SQL Server 会禁止对表的访问吗
2014/04/28 面试题
优秀的计算机专业求职信范文
2013/12/27 职场文书
毕业自我评价
2014/02/05 职场文书
保护环境标语
2014/06/09 职场文书
学习三严三实对照检查材料思想汇报
2014/09/22 职场文书
奖金申请报告模板
2015/05/15 职场文书
2015年征兵工作总结
2015/07/23 职场文书
2016年共产党员公开承诺书
2016/03/24 职场文书
Python如何把不同类型数据的json序列化
2021/04/30 Python
Python中OpenCV实现查找轮廓的实例
2021/06/08 Python