Ping3 简介#
Ping3 是纯 Python3 版本的 ICMP ping 实现,使用了 raw socket。(需要注意的是,在一些平台上,只有以 root 权限运行的进程才能发送 ICMP 消息。)
from ping3 import ping, verbose_ping
ping('example.com') # Returns delay in seconds.
---------------------------------------------------------------------------
PermissionError Traceback (most recent call last)
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py:281, in ping(dest_addr, timeout, unit, src_addr, ttl, seq, size, interface)
280 try:
--> 281 sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
282 except PermissionError as err:
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/socket.py:233, in socket.__init__(self, family, type, proto, fileno)
232 proto = 0
--> 233 _socket.socket.__init__(self, family, type, proto, fileno)
234 self._io_refs = 0
PermissionError: [Errno 1] Operation not permitted
During handling of the above exception, another exception occurred:
PermissionError Traceback (most recent call last)
Cell In[2], line 1
----> 1 ping('example.com') # Returns delay in seconds.
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py:83, in _func_logger.<locals>.wrapper(*args, **kwargs)
81 all_args = ", ".join((pargs, kargs)) if (pargs and kargs) else (pargs or kargs)
82 _debug("Function called:", "{func.__name__}({})".format(all_args, func=func))
---> 83 func_return = func(*args, **kwargs)
84 _debug("Function returned:", "{func.__name__} -> {rtrn}".format(func=func, rtrn=func_return))
85 return func_return
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py:285, in ping(dest_addr, timeout, unit, src_addr, ttl, seq, size, interface)
283 if err.errno == errno.EPERM: # [Errno 1] Operation not permitted
284 _debug("`{}` when create socket.SOCK_RAW, using socket.SOCK_DGRAM instead.".format(err))
--> 285 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_ICMP)
286 else:
287 raise err
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/socket.py:233, in socket.__init__(self, family, type, proto, fileno)
231 if proto == -1:
232 proto = 0
--> 233 _socket.socket.__init__(self, family, type, proto, fileno)
234 self._io_refs = 0
235 self._closed = False
PermissionError: [Errno 13] Permission denied
verbose_ping('example.com') # Ping 4 times in a row.
---------------------------------------------------------------------------
PermissionError Traceback (most recent call last)
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py:281, in ping(dest_addr, timeout, unit, src_addr, ttl, seq, size, interface)
280 try:
--> 281 sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
282 except PermissionError as err:
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/socket.py:233, in socket.__init__(self, family, type, proto, fileno)
232 proto = 0
--> 233 _socket.socket.__init__(self, family, type, proto, fileno)
234 self._io_refs = 0
PermissionError: [Errno 1] Operation not permitted
During handling of the above exception, another exception occurred:
PermissionError Traceback (most recent call last)
Cell In[3], line 1
----> 1 verbose_ping('example.com') # Ping 4 times in a row.
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py:83, in _func_logger.<locals>.wrapper(*args, **kwargs)
81 all_args = ", ".join((pargs, kargs)) if (pargs and kargs) else (pargs or kargs)
82 _debug("Function called:", "{func.__name__}({})".format(all_args, func=func))
---> 83 func_return = func(*args, **kwargs)
84 _debug("Function returned:", "{func.__name__} -> {rtrn}".format(func=func, rtrn=func_return))
85 return func_return
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py:351, in verbose_ping(dest_addr, count, interval, *args, **kwargs)
349 output_text += " from '{}'".format(src) if src else ""
350 output_text += " ... "
--> 351 delay = ping(dest_addr, seq=i, *args, **kwargs)
352 print(output_text, end="")
353 if delay is None:
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py:83, in _func_logger.<locals>.wrapper(*args, **kwargs)
81 all_args = ", ".join((pargs, kargs)) if (pargs and kargs) else (pargs or kargs)
82 _debug("Function called:", "{func.__name__}({})".format(all_args, func=func))
---> 83 func_return = func(*args, **kwargs)
84 _debug("Function returned:", "{func.__name__} -> {rtrn}".format(func=func, rtrn=func_return))
85 return func_return
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py:285, in ping(dest_addr, timeout, unit, src_addr, ttl, seq, size, interface)
283 if err.errno == errno.EPERM: # [Errno 1] Operation not permitted
284 _debug("`{}` when create socket.SOCK_RAW, using socket.SOCK_DGRAM instead.".format(err))
--> 285 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_ICMP)
286 else:
287 raise err
File /opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/socket.py:233, in socket.__init__(self, family, type, proto, fileno)
231 if proto == -1:
232 proto = 0
--> 233 _socket.socket.__init__(self, family, type, proto, fileno)
234 self._io_refs = 0
235 self._closed = False
PermissionError: [Errno 13] Permission denied
支持命令行模式:
!ping3 example.com # Verbose ping
Traceback (most recent call last):
File "/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py", line 281, in ping
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/socket.py", line 233, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
PermissionError: [Errno 1] Operation not permitted
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/hostedtoolcache/Python/3.12.8/x64/bin/ping3", line 8, in <module>
sys.exit(main())
^^^^^^
File "/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/command_line.py", line 33, in main
ping3.verbose_ping(addr, count=args.count, ttl=args.ttl, timeout=args.timeout, size=args.size, interval=args.interval, interface=args.interface, src_addr=args.src_addr)
File "/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py", line 83, in wrapper
func_return = func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py", line 351, in verbose_ping
delay = ping(dest_addr, seq=i, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py", line 83, in wrapper
func_return = func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/site-packages/ping3/__init__.py", line 285, in ping
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_ICMP)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.8/x64/lib/python3.12/socket.py", line 233, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
PermissionError: [Errno 13] Permission denied
函数模式:
示例:
>>> from ping3 import ping, verbose_ping
>>> ping('example.com') # Returns delay in seconds.
0.215697261510079666 # `0.0` returned means the delay is lower than the precision of `time.time()`.
>>> ping('not.exist.com') # If host unknown (cannot resolve), returns False.
False
>>> ping("224.0.0.0") # If timed out (no reply), returns None.
None
>>> ping('example.com', timeout=10) # Set timeout to 10 seconds. Default timeout is 4 for 4 seconds.
0.215697261510079666
>>> ping('example.com', unit='ms') # Returns delay in milliseconds. Default unit is 's' for seconds.
215.9627876281738
>>> ping('example.com', src_addr='192.168.1.15') # Set source ip address for multiple interfaces. Default src_addr is None for no binding.
0.215697261510079666
>>> ping('example.com', interface='eth0') # LINUX ONLY. Set source interface for multiple network interfaces. Default interface is None for no binding.
0.215697261510079666
>>> ping('example.com', ttl=5) # Set packet Time-To-Live to 5. The packet is discarded if it does not reach the target host after 5 jumps. Default ttl is 64.
None
>>> ping('example.com', size=56) # Set ICMP packet payload to 56 bytes. The total ICMP packet size is 8 (header) + 56 (payload) = 64 bytes. Default size is 56.
0.215697261510079666
>>> verbose_ping('example.com') # Ping 4 times in a row.
ping 'example.com' ... 215ms
ping 'example.com' ... 216ms
ping 'example.com' ... 219ms
ping 'example.com' ... 217ms
>>> verbose_ping('example.com', timeout=10) # Set timeout to 10 seconds. Default timeout is 4 for 4 seconds.
ping 'example.com' ... 215ms
ping 'example.com' ... 216ms
ping 'example.com' ... 219ms
ping 'example.com' ... 217ms
>>> verbose_ping('example.com', count=6) # Ping 6 times. Default count is 4.
ping 'example.com' ... 215ms
ping 'example.com' ... 216ms
ping 'example.com' ... 219ms
ping 'example.com' ... 217ms
ping 'example.com' ... 215ms
ping 'example.com' ... 216ms
>>> verbose_ping('example.com', count=0) # Ping endlessly (0 means infinite loops). Using `ctrl + c` to stop manully.
ping 'example.com' ... 215ms
...
>>> verbose_ping('example.com', src_addr='192.168.1.15') # Ping from source IP address for multiple interfaces. Default src_addr is None.
ping 'example.com' from '192.168.1.15' ... 215ms
ping 'example.com' from '192.168.1.15' ... 216ms
ping 'example.com' from '192.168.1.15' ... 219ms
ping 'example.com' from '192.168.1.15' ... 217ms
>>> verbose_ping('example.com', interface='wifi0') # LINUX ONLY. Ping from network interface 'wifi0'. Default interface is None.
ping 'example.com' from '192.168.1.15' ... 215ms
ping 'example.com' from '192.168.1.15' ... 216ms
ping 'example.com' from '192.168.1.15' ... 219ms
ping 'example.com' from '192.168.1.15' ... 217ms
>>> verbose_ping('example.com', unit='s') # Displays delay in seconds. Default unit is "ms" for milliseconds.
ping 'example.com' ... 1s
ping 'example.com' ... 2s
ping 'example.com' ... 1s
ping 'example.com' ... 1s
>>> verbose_ping('example.com', ttl=5) # Set TTL to 5. Default is 64.
ping 'example.com' ... Timeout
ping 'example.com' ... Timeout
ping 'example.com' ... Timeout
ping 'example.com' ... Timeout
>>> verbose_ping('example.com', interval=5) # Wait 5 seconds between each packet. Default is 0.
ping 'example.com' ... 215ms # wait 5 secs
ping 'example.com' ... 216ms # wait 5 secs
ping 'example.com' ... 219ms # wait 5 secs
ping 'example.com' ... 217ms
>>> verbose_ping('example.com', size=56) # Set ICMP payload to 56 bytes. Default size is 56.
ping 'example.com' ... 215ms
ping 'example.com' ... 216ms
ping 'example.com' ... 219ms
ping 'example.com' ... 217ms
DEBUG 模式#
示例:
>>> import ping3
>>> ping3.DEBUG = True # Default is False.
>>> ping3.ping("example.com") # "ping()" prints received IP header and ICMP header.
[DEBUG] IP HEADER: {'version': 69, 'tos': 0, 'len': 14336, 'id': 8620, 'flags': 0, 'ttl': 51, 'protocol': 1, 'checksum': *, 'src_addr': *, 'dest_addr': *}
[DEBUG] ICMP HEADER: {'type': 0, 'code': 0, 'checksum': 8890, 'id': 21952, 'seq': 0}
0.215697261510079666
>>> ping3.ping("example.com", timeout=0.0001)
[DEBUG] Request timeout for ICMP packet. (Timeout = 0.0001s)
None
>>> ping3.ping("not.exist.com")
[DEBUG] Cannot resolve: Unknown host. (Host = not.exist.com)
False
>>> ping3.ping("example.com", ttl=1)
[DEBUG] Time exceeded: Time To Live expired.
None
异常模式#
在出现错误时引发异常,而不是返回 None
>>> import ping3
>>> ping3.EXCEPTIONS = True # Default is False.
>>> ping3.ping("example.com", timeout=0.0001)
[... Traceback ...]
ping3.errors.Timeout: Request timeout for ICMP packet. (Timeout = 0.0001s)
>>> ping3.ping("not.exist.com")
[... Traceback ...]
ping3.errors.HostUnknown: Cannot resolve: Unknown host. (Host = not.exist.com)
>>> ping3.ping("example.com", ttl=1) # Linux need root privilege to receive TTL expired. Windows cannot get TTL expired.
[... Traceback ...]
ping3.errors.TimeToLiveExpired: Time exceeded: Time To Live expired.
>>> try:
>>> ping3.ping("example.com", ttl=1)
>>> except ping3.errors.TimeToLiveExpired as err:
>>> print(err.ip_header["src_addr"]) # TimeToLiveExpired, DestinationUnreachable and DestinationHostUnreachable have ip_header and icmp_header attached.
1.2.3.4 # IP address where the TTL happened.
>>> help(ping3.errors) # More info about exceptions.
!ping3 -h
usage: ping3 [-h] [-v] [-c COUNT] [-t TIMEOUT] [-i INTERVAL] [-I INTERFACE]
[-S SRC_ADDR] [-T TTL] [-s SIZE] [-D] [-E]
[DEST_ADDR ...]
A pure python3 version of ICMP ping implementation using raw socket.
positional arguments:
DEST_ADDR The destination address, can be an IP address or a
domain name. Ex. 192.168.1.1/example.com.
options:
-h, --help show this help message and exit
-v, --version show program's version number and exit
-c COUNT, --count COUNT
How many pings should be sent. Default is 4.
-t TIMEOUT, --timeout TIMEOUT
Time to wait for a response, in seconds. Default is 4.
-i INTERVAL, --interval INTERVAL
Time to wait between each packet, in seconds. Default
is 0.
-I INTERFACE, --interface INTERFACE
LINUX ONLY. The gateway network interface to ping
from. Default is None.
-S SRC_ADDR, --src SRC_ADDR
The IP address to ping from. This is for multiple
network interfaces. Default is None
-T TTL, --ttl TTL The Time-To-Live of the outgoing packet. Default is
64.
-s SIZE, --size SIZE The ICMP packet payload size in bytes. Default is 56.
-D, --debug Turn on DEBUG mode.
-E, --exceptions Turn on EXCEPTIONS mode.
!!Note: ICMP messages can only be sent from processes running as root.