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生成词云的实现方法(推荐)
Jun 13 Python
python 生成器协程运算实例
Sep 04 Python
django框架之cookie/session的使用示例(小结)
Oct 15 Python
对python的输出和输出格式详解
Dec 08 Python
python利用跳板机ssh远程连接redis的方法
Feb 19 Python
Django CSRF跨站请求伪造防护过程解析
Jul 31 Python
python如何将两个txt文件内容合并
Oct 18 Python
python递归调用中的坑:打印有值, 返回却None
Mar 16 Python
python 引用传递和值传递详解(实参,形参)
Jun 05 Python
django restframework serializer 增加自定义字段操作
Jul 15 Python
如何使用PyCharm引入需要使用的包的方法
Sep 22 Python
详解Scrapy Redis入门实战
Nov 18 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实现把数字ID转字母ID
2013/08/12 PHP
PHP把网页保存为word文件的三种方法
2014/04/01 PHP
PHP使用MPDF类生成PDF的方法
2015/12/08 PHP
php文件上传类的分享
2017/07/06 PHP
thinkPHP5.0框架验证码调用及点击图片刷新简单实现方法
2018/09/07 PHP
推荐自用 Javascript 缩图函数 (onDOMLoaded)……
2007/10/23 Javascript
使用JavaScript检测Firefox浏览器是否启用了Firebug的代码
2010/12/28 Javascript
JS中捕获console.log()输出的方法
2015/04/16 Javascript
javascript实现简单的页面右下角提示信息框
2015/07/31 Javascript
JavaScript设计模式经典之命令模式
2016/02/24 Javascript
jQuery插件简单学习实例教程
2016/07/01 Javascript
jQuery实现的导航下拉菜单效果
2016/07/04 Javascript
angular.js分页代码的实例
2016/07/27 Javascript
React Js 微信禁止复制链接分享禁止隐藏右上角菜单功能
2017/05/26 Javascript
JS库之wow.js使用方法
2017/09/14 Javascript
解决html-jquery/js引用外部图片时遇到看不了或出现403的问题
2017/09/22 jQuery
ajax请求+vue.js渲染+页面加载的示例
2018/02/11 Javascript
React为 Vue 引入容器组件和展示组件的教程详解
2018/05/03 Javascript
JavaScript&quot;模拟事件&quot;的注意要点详解
2019/02/13 Javascript
js作用域和作用域链及预解析
2019/04/11 Javascript
layer父页获取弹出层输入框里面的值方法
2019/09/02 Javascript
JS实现随机抽选获奖者
2019/11/07 Javascript
three.js利用gpu选取物体并计算交点位置的方法示例
2019/11/25 Javascript
js+h5 canvas实现图片验证码
2020/10/11 Javascript
[03:24]DOTA2超级联赛专访hao 大翻盘就是逆袭
2013/05/24 DOTA
python模拟新浪微博登陆功能(新浪微博爬虫)
2013/12/24 Python
Python 获取ftp服务器文件时间的方法
2019/07/02 Python
MaBelle玛贝尔香港官网:香港钻饰连锁店
2019/09/09 全球购物
Prototype如何实现页面局部定时刷新
2013/08/06 面试题
大二学期个人自我评价
2014/01/13 职场文书
工作迟到检讨书
2014/02/21 职场文书
小学数学国培感言
2014/03/10 职场文书
慈善捐赠倡议书
2014/08/30 职场文书
公务员政审材料范文
2014/12/23 职场文书
2016年中秋节寄语大全
2015/12/07 职场文书
Python爬虫 简单介绍一下Xpath及使用
2022/04/26 Python