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模拟新浪微博登陆功能(新浪微博爬虫)
Dec 24 Python
gearman的安装启动及python API使用实例
Jul 08 Python
Python中zip()函数用法实例教程
Jul 31 Python
Python轻量级ORM框架Peewee访问sqlite数据库的方法详解
Jul 20 Python
python检测文件夹变化,并拷贝有更新的文件到对应目录的方法
Oct 17 Python
python函数修饰符@的使用方法解析
Sep 02 Python
Python+PyQt5+MySQL实现天气管理系统
Jun 16 Python
详解Pycharm与anaconda安装配置指南
Aug 25 Python
python3中calendar返回某一时间点实例讲解
Nov 18 Python
Python爬虫定时计划任务的几种常见方法(推荐)
Jan 15 Python
利用Python如何画一颗心、小人发射爱心
Feb 21 Python
基于注解实现 SpringBoot 接口防刷的方法
Mar 02 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分页函数
2006/07/08 PHP
PHP 学习路线与时间表
2010/02/21 PHP
PHP rawurlencode与urlencode函数的深入分析
2013/06/08 PHP
PHP开发注意事项总结
2015/02/04 PHP
Laravel下生成验证码的类
2017/11/15 PHP
javascript 写类方式之十
2009/07/05 Javascript
js中使用DOM复制(克隆)指定节点名数据到新的XML文件中的代码
2011/07/27 Javascript
关于JS控制代码暂停的实现方法分享
2012/10/11 Javascript
jquery validate poshytip 自定义样式
2012/11/26 Javascript
javascript的原生方法获取数组中的最大(最小)值
2012/12/19 Javascript
使用jQuery避免鼠标双击的解决方案
2013/08/21 Javascript
jQuery中live()方法用法实例
2015/01/19 Javascript
js结合正则实现国内手机号段校验
2015/06/19 Javascript
JS实现仿新浪微博发布内容为空时提示功能代码
2015/08/19 Javascript
bootstrap网格系统使用方法解析
2017/01/13 Javascript
Angular.js指令学习中一些重要属性的用法教程
2017/05/24 Javascript
js中自定义react数据验证组件实例详解
2018/10/19 Javascript
Vue-CLI 3 scp2自动部署项目至服务器的方法
2020/07/24 Javascript
[01:06]DOTA2隆重推出2016冬季勇士令状 内含上海特级锦标赛互动指南
2016/02/17 DOTA
[00:31]DOTA2上海特级锦标赛 Fnatic战队宣传片
2016/03/04 DOTA
python操作MongoDB基础知识
2013/11/01 Python
python判断给定的字符串是否是有效日期的方法
2015/05/13 Python
Django框架中render_to_response()函数的使用方法
2015/07/16 Python
Python获取当前页面内所有链接的四种方法对比分析
2017/08/19 Python
python设定并获取socket超时时间的方法
2019/01/12 Python
Pytorch Tensor 输出为txt和mat格式方式
2020/01/03 Python
Pandas读取csv时如何设置列名
2020/06/02 Python
PyQt5的相对布局管理的实现
2020/08/07 Python
Python pymysql模块安装并操作过程解析
2020/10/13 Python
python中用ggplot绘制画图实例讲解
2021/01/26 Python
关于Java String的一道面试题
2013/09/29 面试题
本科生的职业生涯规划范文
2014/01/09 职场文书
特教教师先进事迹
2014/05/21 职场文书
舞蹈专业求职信
2014/06/13 职场文书
mysql优化
2021/04/06 MySQL
css样式important规则的正确使用方式
2022/06/10 HTML / CSS