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 相关文章推荐
python33 urllib2使用方法细节讲解
Dec 03 Python
pandas DataFrame数据转为list的方法
Apr 11 Python
python得到windows自启动列表的方法
Oct 14 Python
将python图片转为二进制文本的实例
Jan 24 Python
python 使用装饰器并记录log的示例代码
Jul 12 Python
Python利用scapy实现ARP欺骗的方法
Jul 23 Python
Python 使用指定的网卡发送HTTP请求的实例
Aug 21 Python
用Python做一个久坐提醒小助手的示例代码
Feb 10 Python
基于python3的socket聊天编程
Feb 17 Python
利用python实现凯撒密码加解密功能
Mar 31 Python
Python中过滤字符串列表的方法
Dec 22 Python
Python字符串格式化方式
Apr 07 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在XP下IIS和Apache2服务器上的安装
2006/09/05 PHP
DedeCms模板安装/制作概述
2007/03/11 PHP
php for 循环语句使用方法详细说明
2010/05/09 PHP
php通过Chianz.com获取IP地址与地区的方法
2015/01/14 PHP
PHP重载基础知识回顾
2020/09/10 PHP
一个javascript参数的小问题
2008/03/02 Javascript
Javascript中Eval函数的使用
2010/03/23 Javascript
js克隆对象、数组的常用方法介绍
2013/09/26 Javascript
使用window.prompt()实现弹出用户输入的对话框
2015/04/13 Javascript
js数组依据下标删除元素
2015/04/14 Javascript
javascript实现的网站访问量统计代码
2015/12/20 Javascript
jquery拖拽效果完整实例(附demo源码下载)
2016/01/14 Javascript
node.js cookie-parser之parser.js
2016/06/06 Javascript
javascript中Date对象应用之简易日历实现
2016/07/12 Javascript
Ubuntu 16.04 64位中搭建Node.js开发环境教程
2016/10/19 Javascript
jQuery插件ajaxFileUpload使用实例解析
2016/10/19 Javascript
Bootstrap的modal拖动效果
2016/12/25 Javascript
Javascript中字符串相关常用的使用方法总结
2017/03/13 Javascript
jQuery插件HighCharts绘制简单2D柱状图效果示例【附demo源码】
2017/03/21 jQuery
weui框架实现上传、预览和删除图片功能代码
2017/08/24 Javascript
jQuery实现的简单日历组件定义与用法示例
2018/12/24 jQuery
vue-cli3 取消eslint校验代码的解决办法
2020/01/16 Javascript
js实现简单的贪吃蛇游戏
2020/04/23 Javascript
在RedHat系Linux上部署Python的Celery框架的教程
2015/04/07 Python
简单介绍Python中的len()函数的使用
2015/04/07 Python
python3实现磁盘空间监控
2018/06/21 Python
python爬虫 正则表达式解析
2019/09/28 Python
纽约手袋品牌:KARA
2018/03/18 全球购物
急诊科护士自我鉴定
2013/10/14 职场文书
幼儿园教师节活动方案
2014/02/02 职场文书
酒店七夕情人节活动策划方案
2014/08/24 职场文书
党委书记个人检查对照材料思想汇报
2014/10/11 职场文书
2016秋季小学开学寄语
2015/12/03 职场文书
《我是什么》教学反思
2016/02/16 职场文书
MySQL Innodb关键特性之插入缓冲(insert buffer)
2021/04/08 MySQL
Vue接口封装的完整步骤记录
2021/05/14 Vue.js