用 Python ping 一个站点?

2022-01-19 00:00:00 python network-programming ping

问题描述

如何使用 Python ping 网站或 IP 地址?

How do I ping a website or IP address with Python?


解决方案

看这个 纯 Python ping 由 Matthew Dixon Cowles 和 Jens Diemer.另外,请记住 Python 需要 root 才能在 linux 中生成 ICMP(即 ping)套接字.

See this pure Python ping by Matthew Dixon Cowles and Jens Diemer. Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux.

import ping, socket
try:
    ping.verbose_ping('www.google.com', count=3)
    delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
    print "Ping Error:", e

源代码本身很容易阅读,请参阅 verbose_pingPing.do 的实现以获得灵感.

The source code itself is easy to read, see the implementations of verbose_ping and of Ping.do for inspiration.

相关文章