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实现跨文件全局变量的方法
Jul 07 Python
使用python加密自己的密码
Aug 04 Python
qpython3 读取安卓lastpass Cookies
Jun 19 Python
Tensorflow 自带可视化Tensorboard使用方法(附项目代码)
Feb 10 Python
Window 64位下python3.6.2环境搭建图文教程
Sep 19 Python
python中import与from方法总结(推荐)
Mar 21 Python
django框架使用orm实现批量更新数据的方法
Jun 21 Python
python用for循环求和的方法总结
Jul 08 Python
Django中ORM找出内容不为空的数据实例
May 20 Python
python调用私有属性的方法总结
Jul 24 Python
Sublime Text3最新激活注册码分享适用2020最新版 亲测可用
Nov 12 Python
python3中calendar返回某一时间点实例讲解
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下intval()和(int)转换使用与区别
2008/07/18 PHP
php实现设计模式中的单例模式详解
2014/10/11 PHP
PHP 使用redis简单示例分享
2015/03/05 PHP
php for 循环使用的简单实例
2016/06/02 PHP
PHP中in_array的隐式转换的解决方法
2018/03/06 PHP
PHP面向对象程序设计内置标准类,普通数据类型转为对象类型示例
2019/06/12 PHP
thinkphp5实现微信扫码支付
2019/12/23 PHP
laravel数据库查询结果自动转数组修改实例
2021/02/27 PHP
利用jquery的获取JS文件中的字符串内容
2012/02/14 Javascript
如何使用Javascript获取距今n天前的日期
2013/07/08 Javascript
jquery实现预览提交的表单代码分享
2014/05/21 Javascript
基于JavaScript实现回到页面顶部动画代码
2016/05/24 Javascript
jQuery+Ajax+PHP弹出层异步登录效果(附源码下载)
2016/05/27 Javascript
JavaScript中数组Array方法详解
2017/02/27 Javascript
jQuery表格(Table)基本操作实例分析
2017/03/10 Javascript
Vue2.x中的父组件传递数据至子组件的方法
2017/05/01 Javascript
利用canvas中toDataURL()将图片转为dataURL(base64)的方法详解
2017/11/20 Javascript
JS实现的tab页切换效果完整示例
2018/12/18 Javascript
JavaScript 严格模式(use strict)用法实例分析
2020/03/04 Javascript
原生小程序封装跑马灯效果
2020/10/21 Javascript
基于Cesium绘制抛物弧线
2020/11/18 Javascript
推荐11个实用Python库
2015/01/23 Python
python获取android设备的GPS信息脚本分享
2015/03/06 Python
Python 装饰器使用详解
2017/07/29 Python
python函数式编程学习之yield表达式形式详解
2018/03/25 Python
浅谈python 导入模块和解决文件句柄找不到问题
2018/12/15 Python
浅谈Python中eval的强大与危害
2019/03/13 Python
Python爬虫学习之获取指定网页源码
2019/07/30 Python
Django之全局使用request.user.username的实例详解
2020/05/14 Python
使用phonegap进行提示操作的具体方法
2017/03/30 HTML / CSS
房屋租赁意向书
2014/04/01 职场文书
监督检查工作方案
2014/05/28 职场文书
2014年妇联工作总结
2014/11/21 职场文书
2014年路政工作总结
2014/12/10 职场文书
文体活动总结
2015/02/04 职场文书
《仙剑客栈2》第一弹正式宣传片公开 年内发售
2022/04/07 其他游戏