ICMP ping是您遇到过的最常见的网络扫描类型。 打开命令行提示符或终端并输入ping www.google.com非常容易。

为什么要在python中实现?

很多名牌大学喜欢考试用python的socket库实现ICMP协议的ping

个别环境没有ping

直接上代码:

#!/usr/bin/python3

# -*- coding: utf-8 -*-

# 技术支持:https://www.jianshu.com/u/69f40328d4f0

# 技术支持 https://china-testing.github.io/

# https://github.com/china-testing/python-api-tesing/blob/master/practices/ping.py

#qq群144081101 567351477

# CreateDate: 2018-11-22

import os

import argparse

import socket

import struct

import select

import time

ICMP_ECHO_REQUEST = 8 # Platform specific

DEFAULT_TIMEOUT = 2

DEFAULT_COUNT = 4

class Pinger(object):

""" Pings to a host -- the Pythonic way"""

def __init__(self, target_host, count=DEFAULT_COUNT, timeout=DEFAULT_TIMEOUT):

self.target_host = target_host

self.count = count

self.timeout = timeout

def do_checksum(self, source_string):

""" Verify the packet integritity """

sum = 0

max_count = (len(source_string)/2)*2

count = 0

while count < max_count:

val = source_string[count + 1]*256 + source_string[count]

sum = sum + val

sum = sum & 0xffffffff

count = count + 2

if max_count

sum = sum + ord(source_string[len(source_string) - 1])

sum = sum & 0xffffffff

sum = (sum >> 16) + (sum & 0xffff)

sum = sum + (sum >> 16)

answer = ~sum

answer = answer & 0xffff

answer = answer >> 8 | (answer << 8 & 0xff00)

return answer

def receive_pong(self, sock, ID, timeout):

"""

Receive ping from the socket.

"""

time_remaining = timeout

while True:

start_time = time.time()

readable = select.select([sock], [], [], time_remaining)

time_spent = (time.time() - start_time)

if readable[0] == []: # Timeout

return

time_received = time.time()

recv_packet, addr = sock.recvfrom(1024)

icmp_header = recv_packet[20:28]

type, code, checksum, packet_ID, sequence = struct.unpack(

"bbHHh", icmp_header

)

if packet_ID == ID:

bytes_In_double = struct.calcsize("d")

time_sent = struct.unpack("d", recv_packet[28:28 + bytes_In_double])[0]

return time_received - time_sent

time_remaining = time_remaining - time_spent

if time_remaining <= 0:

return

def send_ping(self, sock, ID):

"""

Send ping to the target host

"""

target_addr = socket.gethostbyname(self.target_host)

my_checksum = 0

# Create a dummy heder with a 0 checksum.

header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)

bytes_In_double = struct.calcsize("d")

data = (192 - bytes_In_double) * "Q"

data = struct.pack("d", time.time()) + bytes(data.encode('utf-8'))

# Get the checksum on the data and the dummy header.

my_checksum = self.do_checksum(header + data)

header = struct.pack(

"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1

)

packet = header + data

sock.sendto(packet, (target_addr, 1))

def ping_once(self):

"""

Returns the delay (in seconds) or none on timeout.

"""

icmp = socket.getprotobyname("icmp")

try:

sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)

except socket.error as e:

if e.errno == 1:

# Not superuser, so operation not permitted

e.msg += "ICMP messages can only be sent from root user processes"

raise socket.error(e.msg)

except Exception as e:

print ("Exception: %s" %(e))

my_ID = os.getpid() & 0xFFFF

self.send_ping(sock, my_ID)

delay = self.receive_pong(sock, my_ID, self.timeout)

sock.close()

return delay

def ping(self):

"""

Run the ping process

"""

for i in range(self.count):

print ("Ping to %s..." % self.target_host,)

try:

delay = self.ping_once()

except socket.gaierror as e:

print ("Ping failed. (socket error: '%s')" % e[1])

break

if delay == None:

print ("Ping failed. (timeout within %ssec.)" % self.timeout)

else:

delay = delay * 1000

print ("Get pong in %0.4fms" % delay)

if __name__ == '__main__':

parser = argparse.ArgumentParser(description='Python ping')

parser.add_argument('host', action="store", help=u'主机名')

given_args = parser.parse_args()

target_host = given_args.host

pinger = Pinger(target_host=target_host)

pinger.ping()

参考资料

执行

注意要有root或管理员权限:

# python3 ping.py china-testing.github.io

Ping to china-testing.github.io...

Get pong in 160.7175ms

Ping to china-testing.github.io...

Get pong in 160.8465ms

Ping to china-testing.github.io...

Get pong in 12.0983ms

Ping to china-testing.github.io...

Get pong in 161.3324ms

# python3 ping.py www.so.com

Ping to www.so.com...

Get pong in 29.0303ms

Ping to www.so.com...

Get pong in 28.8599ms

Ping to www.so.com...

Get pong in 28.9860ms

Ping to www.so.com...

Get pong in 29.0167ms

python调用库实现返回ping的时延_python网络作业:使用python的socket库实现ICMP协议的ping...相关推荐

  1. 原生socket使用ICMP协议实现ping单个或多个目标时发生窜包的解决方法

    问题描述 原生socket使用ICMP协议实现ping功能,网上代码很多了,我参考的是这本:王艳平,张越.Windows网络与通信程序设计[M].北京人民邮电出版社,2006. 代码逻辑也很清晰,先构 ...

  2. ICMP协议的ping和tracert应用

    一.实验目的 1.掌握基于ICMP协议的ping和tracert的基本使用方法. 二.实验内容 1.完成ping命令的使用方法和结果演示. 2.完成tracert命令的使用方法和结果演示. 三.实验过 ...

  3. 【转】:TCP/IP详解学习笔记(4)-ICMP协议,ping和Traceroute

    TCP/IP详解学习笔记(4)-ICMP协议,ping和Traceroute 分类:            TCP/IP详解学习笔记计算机网络2006-04-20 18:147970人阅读评论(1)收 ...

  4. python调用库实现返回ping的时延_python在windows下实现ping操作并接收返回信息

    python 执行ping 返回成功与否你自己不将自己想在心里,倒也没关系,有我将你摆在心里就够了. 需分享python实时返回ping回包,怎么写我宁愿两个人的自尊一起摔的四分五裂,一起同归于尽,我 ...

  5. python 调用mysql存储过程返回结果集

    存储过程: delimiter | create procedure get_product_info(in imid int(10),int iuser varchar(20)) begin sel ...

  6. python 调用vba 参数 保存表格_Jupyter Notebooks嵌入Excel并使用Python替代VBA宏

    以前,Excel和Python Jupyter Notebook之间我们只能选择一个. 但是现在随着PyXLL-Jupyter软件包的推出,可以将两者一起使用. 在本文中,我将向你展示如何设置在Exc ...

  7. python调用r语言加载包错误_Python调用R语言

    网络上经常看到有人问数据分析是学习Python好还是R语言好,还有一些争论Python好还是R好的文章.每次看到这样的文章我都会想到李舰和肖凯的<数据科学中的R语言>,书中一直强调,工具不 ...

  8. 如何将c语言程序封装供python调用_一起学opencv-python四十五:opencv绑定python,python和c++互调...

    opencv-python系列教程来到了最后一讲.感谢一路的坚持. 如何生成OpenCV-Python绑定? 在OpenCV中,所有算法都是用C ++实现的.但是这些算法可以用于不同的语言,如Pyth ...

  9. python调用matlab环境配置、非常详细!!!_Python调用Matlab2014b引擎

    用惯Python的你,是不是早已无法忍受matplotlib那丑陋无比的图以及蛋疼无比部署依赖? 当当当当,Matlab2014b的Python Engine API现已加入豪华午餐. 上次写了一篇文 ...

最新文章

  1. 目前python主要应用领域零售_python3读取HDA零售企业数据(一)
  2. 常用的php开发工具有哪些?
  3. 006-spring-data-elasticsearch 3.0.0.0使用【四】-spring-data之Elasticsearch Repositories
  4. 神策数据联合Ping++,推出电商、O2O 行业的 GMV 增长研讨
  5. app开发人脸登录和指纹登录_易讯云通讯推出“一键登录”,为App登录提供新方案...
  6. 我们还很时尚freeeim
  7. springboot系列(三) 启动类中关键注解作用解析
  8. PAT 乙级 1044. 火星数字(20) Java版
  9. 使用CSS 媒体查询功能满足不同屏幕分辨率要求
  10. C++ 学习之旅三——我和超级玛丽有个约会
  11. 机器学习中分类和聚类的区别
  12. CGI编程学习----查询2000W开房数据
  13. Suppressing Uncertainties for Large-Scale Facial Expression Recognition(2020CVPR)
  14. 计算机专业论文的创新点怎么说,计算机专业毕业生如何写毕业论文
  15. label confusion learning to enhance text classification models
  16. java 实心圆_java JFrame窗口中画一个实心圆并设置背景颜色,但背景不显示,级求解!!...
  17. ps进行透视变换(扭曲变换)
  18. cf(穿越火线)进游戏乱码问题解决方案
  19. Oracle中if...then的使用
  20. C++17新特性总结

热门文章

  1. python 数据离散化和面元划分
  2. arcgis-online-python-scripts
  3. (十)java springboot b2b2c shop 多用户商城系统源码:服务网关zuul初级篇
  4. 老板,年终奖我不要了,请给我一部华为Mate RS保时捷设计手机
  5. 七种设计原则(二)单一职责原则
  6. sql 某字段存储另一个表的多个id值并以逗号分隔,现根据id去中文并拼接同样以逗号分隔...
  7. swift2.2的新特性
  8. CSS系列:CSS中盒子模型
  9. centos自启动脚本
  10. UrlEncode编码算法