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分析git log日志示例
Feb 27 Python
Python正则表达式教程之一:基础篇
Mar 02 Python
Python生成器定义与简单用法实例分析
Apr 30 Python
Python面向对象程序设计类的封装与继承用法示例
Apr 12 Python
python的依赖管理的实现
May 14 Python
对Python中TKinter模块中的Label组件实例详解
Jun 14 Python
python实现梯度下降法
Mar 24 Python
python基于socket函数实现端口扫描
May 28 Python
python如何设置静态变量
Sep 07 Python
python如何利用cv2模块读取显示保存图片
Jun 04 Python
如何利用python实现Simhash算法
Jun 28 Python
Python可视化神器pyecharts绘制地理图表
Jul 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
thinkphp模板的包含与渲染实例分析
2014/11/26 PHP
学习php设计模式 php实现装饰器模式(decorator)
2015/12/07 PHP
php中this关键字用法分析
2016/12/07 PHP
Yii2框架中使用PHPExcel导出Excel文件的示例
2017/08/09 PHP
ThinkPHP5.1框架数据库链接和增删改查操作示例
2019/08/03 PHP
win10下 php安装seaslog扩展的详细步骤
2020/12/04 PHP
JQuery textlimit 显示用户输入的字符数 限制用户输入的字符数
2009/05/14 Javascript
js星星评分效果
2014/07/24 Javascript
Three.js利用orbit controls插件(轨道控制)控制模型交互动作详解
2017/09/25 Javascript
微信小程序实现全国机场索引列表
2018/01/31 Javascript
Vue.js 踩坑记之双向绑定
2018/05/03 Javascript
jQuery实现百度图片移入移出内容提示框上下左右移动的效果
2018/06/05 jQuery
JQuery特殊效果和链式调用操作示例
2019/05/13 jQuery
Js生成随机数/随机字符串的方法小结【5种方法】
2020/05/27 Javascript
[01:11:32]VG vs FNATIC 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
从零学Python之hello world
2014/05/21 Python
跟老齐学Python之从if开始语句的征程
2014/09/14 Python
Python网络爬虫与信息提取(实例讲解)
2017/08/29 Python
基于Python __dict__与dir()的区别详解
2017/10/30 Python
Python语言检测模块langid和langdetect的使用实例
2019/02/19 Python
pyenv与virtualenv安装实现python多版本多项目管理
2019/08/17 Python
详解Python图像处理库Pillow常用使用方法
2019/09/02 Python
keras中的History对象用法
2020/06/19 Python
Django-simple-captcha验证码包使用方法详解
2020/11/28 Python
python使用scapy模块实现ARP扫描的过程
2021/01/21 Python
html5视频自动横过来自适应页面且点击播放功能的实现
2020/06/03 HTML / CSS
J2ee常用的设计模式?说明工厂模式
2015/05/21 面试题
自主招生自荐信范文
2015/03/04 职场文书
手机销售员岗位职责
2015/04/11 职场文书
任命书格式范文
2015/09/22 职场文书
小学英语教学反思范文
2016/02/15 职场文书
导游词之山东红叶谷
2019/10/31 职场文书
Python中for后接else的语法使用
2021/05/18 Python
MySQL为id选择合适的数据类型
2021/06/07 MySQL
总结几个非常实用的Python库
2021/06/26 Python
MyBatis 动态SQL全面详解
2021/10/05 MySQL