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 自动安装 Rising 杀毒软件
Apr 24 Python
常用python编程模板汇总
Feb 12 Python
Python实现随机生成有效手机号码及身份证功能示例
Jun 05 Python
用不到50行的Python代码构建最小的区块链
Nov 16 Python
基于python神经卷积网络的人脸识别
May 24 Python
python 将list转成字符串,中间用符号分隔的方法
Oct 23 Python
numpy 计算两个数组重复程度的方法
Nov 07 Python
python 顺时针打印矩阵的超简洁代码
Nov 14 Python
使用Django简单编写一个XSS平台的方法步骤
Mar 25 Python
浅析PEP570新语法: 只接受位置参数
Oct 15 Python
Python with关键字,上下文管理器,@contextmanager文件操作示例
Oct 17 Python
python shell命令行中import多层目录下的模块操作
Mar 09 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
正则表达式语法
2006/10/09 Javascript
深入解析yii权限分级式访问控制的实现(非RBAC法)
2013/06/13 PHP
什么是PEAR?什么是PECL?PHP中两个容易混淆的概念解释
2015/07/01 PHP
Cygwin中安装PHP方法步骤
2015/07/04 PHP
Laravel框架基于ajax和layer.js实现无刷新删除功能示例
2019/01/17 PHP
laravel框架语言包拓展实现方法分析
2019/11/22 PHP
php使用fputcsv实现大数据的导出操作详解
2020/02/27 PHP
6个常见的 PHP 安全性攻击实例和阻止方法
2020/12/16 PHP
JavaScript 联动的无限级封装类,数据采用非Ajax方式,随意添加联动
2010/06/29 Javascript
jquery.pagination.js 无刷新分页实现步骤分享
2012/05/23 Javascript
Jquery 获取对象的几种方式介绍
2014/01/17 Javascript
设计模式中的facade外观模式在JavaScript开发中的运用
2016/05/18 Javascript
node.js cookie-parser之parser.js
2016/06/06 Javascript
浅谈js for循环输出i为同一值的问题
2017/03/01 Javascript
JavaScript实现带有子菜单和控件的slider轮播图效果
2017/11/01 Javascript
使用vue-router与v-if实现tab切换遇到的问题及解决方法
2018/09/07 Javascript
Angular 中使用 FineReport不显示报表直接打印预览
2019/08/21 Javascript
vue v-on:click传递动态参数的步骤
2020/09/11 Javascript
Node快速切换版本、版本回退(降级)、版本更新(升级)
2021/01/07 Javascript
[43:48]Ti4正赛第一天 VG vs NEWBEE 2
2014/07/19 DOTA
python获取一组汉字拼音首字母的方法
2015/07/01 Python
Python实现分段线性插值
2018/12/17 Python
Python Threading 线程/互斥锁/死锁/GIL锁
2019/07/21 Python
python 定时器每天就执行一次的实现代码
2019/08/14 Python
解决Django layui {{}}冲突的问题
2019/08/29 Python
Pytest框架之fixture的详细使用教程
2020/04/07 Python
免费获得微软MCSD证书赶快行动吧!
2012/11/13 HTML / CSS
Mytheresa英国官网:拥有160多个奢侈品品牌
2016/10/09 全球购物
新西兰廉价汽车租赁:Snap Rentals
2018/09/14 全球购物
个人素质的自我评价分享
2013/12/16 职场文书
生产部管理制度
2014/01/31 职场文书
大学学风建设方案
2014/05/04 职场文书
毕业生评语大全
2015/01/04 职场文书
2015年消费者权益日活动总结
2015/02/09 职场文书
读《解忧杂货店》有感:请相信一切都是最好的安排
2019/11/07 职场文书
python模块与C和C++动态库相互调用实现过程示例
2021/11/02 Python