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实现方便使用的级联进度信息实例
May 05 Python
浅谈python中的__init__、__new__和__call__方法
Jul 18 Python
基于Django filter中用contains和icontains的区别(详解)
Dec 12 Python
Python序列循环移位的3种方法推荐
Apr 09 Python
django框架防止XSS注入的方法分析
Jun 21 Python
python  文件的基本操作 菜中菜功能的实例代码
Jul 17 Python
关于pytorch中网络loss传播和参数更新的理解
Aug 20 Python
django 多对多表的创建和插入代码实现
Sep 09 Python
Python从入门到精通之环境搭建教程图解
Sep 26 Python
使用python脚本自动生成K8S-YAML的方法示例
Jul 12 Python
Pycharm创建文件时自动生成文件头注释(自定义设置作者日期)
Nov 24 Python
python实现简单反弹球游戏
Apr 12 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
使用sockets:从新闻组中获取文章(三)
2006/10/09 PHP
php json_encode奇怪问题说明
2011/09/27 PHP
使用php批量删除数据库下所有前缀为prefix_的表
2014/06/09 PHP
php魔术变量用法实例详解
2014/11/13 PHP
ecshop实现smtp发送邮件
2015/02/03 PHP
php抽象类使用要点与注意事项分析
2015/02/09 PHP
php获取给定日期相差天数的方法分析
2017/02/20 PHP
Thinkphp结合AJAX长轮询实现PC与APP推送详解
2017/07/31 PHP
JavaScript实用技巧(一)
2010/08/16 Javascript
鼠标滑上去后图片放大浮出效果的js代码
2011/05/28 Javascript
JQuery+Ajax无刷新分页的实例代码
2014/02/08 Javascript
jQuery给动态添加的元素绑定事件的方法
2015/03/09 Javascript
浅谈JS中json数据的处理
2016/06/30 Javascript
使用jQuery Ajax 请求webservice来实现更简练的Ajax
2016/08/04 Javascript
JS控制TreeView的结点选择
2016/11/11 Javascript
详解Angular路由 ng-route和ui-router的区别
2017/05/22 Javascript
VueJS事件处理器v-on的使用方法
2017/09/27 Javascript
ES6知识点整理之函数对象参数默认值及其解构应用示例
2019/04/17 Javascript
一文读懂ES7中的javascript修饰器
2019/05/06 Javascript
微信公众号生成新浪短网址的实现(快速生成)
2019/08/18 Javascript
JavaScript进阶(一)变量声明提升实例分析
2020/05/09 Javascript
[45:25]OG vs EG 2019国际邀请赛淘汰赛 胜者组 BO3 第一场 8.22
2019/09/05 DOTA
Python使用正则表达式获取网页中所需要的信息
2018/01/29 Python
使用pandas模块读取csv文件和excel表格,并用matplotlib画图的方法
2018/06/22 Python
python3对接mysql数据库实例详解
2019/04/30 Python
pyqt5 键盘监听按下enter 就登陆的实例
2019/06/25 Python
英国最大的专业户外零售商:Mountain Warehouse
2018/06/06 全球购物
维多利亚的秘密阿联酋官网:Victoria’s Secret阿联酋
2019/12/07 全球购物
土木工程专业大学毕业生求职信
2013/10/13 职场文书
小学生元旦广播稿
2014/02/21 职场文书
公司年会抽奖活动主持词
2014/03/31 职场文书
县政府办公室领导班子对照检查材料思想汇报
2014/09/28 职场文书
英文版辞职信
2015/02/28 职场文书
在职人员跳槽求职信
2015/03/20 职场文书
2015年社区综治工作总结
2015/04/21 职场文书
InterProcessMutex实现zookeeper分布式锁原理
2022/03/21 Java/Android