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中进程和线程的区别详解
Oct 29 Python
详解Python中的分组函数groupby和itertools)
Jul 11 Python
解决PyCharm import torch包失败的问题
Oct 13 Python
python异步存储数据详解
Mar 19 Python
Python求离散序列导数的示例
Jul 10 Python
Python 控制终端输出文字的实例
Jul 12 Python
python3.6 tkinter实现屏保小程序
Jul 30 Python
pycharm 批量修改变量名称的方法
Aug 01 Python
python获取Linux发行版名称
Aug 30 Python
python实现XML解析的方法解析
Nov 16 Python
使用tensorboard可视化loss和acc的实例
Jan 21 Python
opencv中图像叠加/图像融合/按位操作的实现
Apr 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
PHP中获取内网用户MAC地址(WINDOWS/linux)的实现代码
2011/08/11 PHP
如何写php守护进程(Daemon)
2015/12/30 PHP
PHP微信开发之查询微信精选文章
2016/06/23 PHP
PHP链表操作简单示例
2016/10/15 PHP
php中通用的excel导出方法实例
2017/12/30 PHP
PHP排序算法之简单选择排序(Simple Selection Sort)实例分析
2018/04/20 PHP
IE下JS读取xml文件示例代码
2013/08/05 Javascript
node.js中的fs.renameSync方法使用说明
2014/12/16 Javascript
基于BootStrap Metronic开发框架经验小结【一】框架总览及菜单模块的处理
2016/05/12 Javascript
用jquery快速解决IE输入框不能输入的问题
2016/10/04 Javascript
jQuery验证表单格式的使用方法
2017/01/10 Javascript
jQuery设置图片等比例缩小的方法
2017/04/29 jQuery
Vue.js教程之axios与网络传输的学习实践
2017/04/29 Javascript
20行js代码实现的贪吃蛇小游戏
2017/06/20 Javascript
jQuery实现拼图小游戏(实例讲解)
2017/07/24 jQuery
微信小程序中button组件的边框设置的实例详解
2017/09/27 Javascript
vue-router 源码之实现一个简单的 vue-router
2018/07/02 Javascript
JS实现显示当前日期的实例代码
2018/07/03 Javascript
微信小程序新闻网站详情页实例代码
2020/01/10 Javascript
[07:06]2018DOTA2国际邀请赛寻真——卫冕冠军Team Liquid
2018/08/10 DOTA
[42:32]Secret vs Optic 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
python网络编程学习笔记(二):socket建立网络客户端
2014/06/09 Python
python批量修改文件夹及其子文件夹下的文件内容
2019/03/15 Python
python异常触发及自定义异常类解析
2019/08/06 Python
Python数据正态性检验实现过程
2020/04/18 Python
css3中background新增的4个新的相关属性用法介绍
2013/09/26 HTML / CSS
CSS3中的content属性使用示例
2015/07/20 HTML / CSS
草莓网美国官网:Strawberrynet USA
2016/12/11 全球购物
初中考试作弊检讨书
2014/02/01 职场文书
建筑施工安全生产责任书
2014/07/22 职场文书
2014标准社保办理委托书
2014/10/06 职场文书
2014年招商工作总结
2014/11/22 职场文书
2015年学校安全管理工作总结
2015/05/11 职场文书
2015年迎新晚会策划书
2015/07/16 职场文书
你有一份《诚信考试承诺书》待领取
2019/11/13 职场文书
pytorch 两个GPU同时训练的解决方案
2021/06/01 Python