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 30 Python
压缩包密码破解示例分享(类似典破解)
Jan 17 Python
Python进程间通信用法实例
Jun 04 Python
python 性能优化方法小结
Mar 31 Python
对python借助百度云API对评论进行观点抽取的方法详解
Feb 21 Python
Python (Win)readline和tab补全的安装方法
Aug 27 Python
Python 脚本的三种执行方式小结
Dec 21 Python
python实现从ftp服务器下载文件
Mar 03 Python
使用 Python 读取电子表格中的数据实例详解
Apr 17 Python
解决Python Matplotlib绘图数据点位置错乱问题
May 16 Python
Python使用sys.exc_info()方法获取异常信息
Jul 23 Python
python 基于selectors库实现文件上传与下载
Dec 31 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自动加载的两种实现方法
2010/06/21 PHP
php学习笔记 面向对象中[接口]与[多态性]的应用
2011/06/16 PHP
PHP获取MSN好友列表类的实现代码
2013/06/23 PHP
php导入excel文件到mysql数据库的方法
2015/01/14 PHP
FireFox JavaScript全局Event对象
2009/06/14 Javascript
LazyForm jQuery plugin 定制您的CheckBox Radio和Select
2009/10/24 Javascript
JS弹出对话框返回值代码(asp.net后台)
2010/12/28 Javascript
JQuery1.6 使用方法三
2011/11/23 Javascript
Javascript计算两个marker之间的距离(Google Map V3)
2013/04/26 Javascript
div模拟滚动条效果示例代码
2013/10/16 Javascript
js实现页面跳转的五种方法推荐
2016/03/10 Javascript
JavaScript的Ext JS框架中的GridPanel组件使用指南
2016/05/21 Javascript
如何检测JavaScript的各种类型
2016/07/30 Javascript
详解用Node.js实现Restful风格webservice
2017/09/29 Javascript
AngularJS对动态增加的DOM实现ng-keyup事件示例
2018/03/12 Javascript
jQuery简单实现的HTML页面文本框模糊匹配查询功能完整示例
2018/05/09 jQuery
Vue中使用sass实现换肤功能
2018/09/07 Javascript
微信小程序进入广告实现代码实例
2019/09/19 Javascript
Vuex模块化应用实践示例
2020/02/03 Javascript
在Python中使用swapCase()方法转换大小写的教程
2015/05/20 Python
Python使用matplotlib绘制余弦的散点图示例
2018/03/14 Python
Python弹出输入框并获取输入值的实例
2019/06/18 Python
python 将字符串中的数字相加求和的实现
2019/07/18 Python
在python中用url_for构造URL的方法
2019/07/25 Python
python脚本实现音频m4a格式转成MP3格式的实例代码
2019/10/09 Python
详解python中eval函数的作用
2019/10/22 Python
Python+opencv+pyaudio实现带声音屏幕录制
2019/12/23 Python
Python面向对象原理与基础语法详解
2020/01/02 Python
html5 桌面提醒:Notifycations应用介绍
2012/11/27 HTML / CSS
英国皇家造币厂:The Royal Mint
2018/10/05 全球购物
护士检查书
2014/01/17 职场文书
科技开发中心办公室主任岗位责任制
2014/02/10 职场文书
赔偿协议书范本
2014/04/15 职场文书
《黄道婆》教学反思
2016/02/22 职场文书
青年人初次创业的“五不要”
2019/08/23 职场文书
Android移动应用开发指南之六种布局详解
2022/09/23 Java/Android