使用 python 对 ipv6 网站进行 tcp ping

tcp ping for ipv6 websites using python

我是 python 的新手。我想通过 TCP ping IPv6 网站。以下代码成功地在 IPv4 网站上执行 ping 操作。但它对 IPv6 网站失败。我还需要 ping IPv6 网站。

是否有任何可能的解决方案来通过 TCP ping ipv6 网站。

代码如下:

import sys
import socket
import time
import signal
from timeit import default_timer as timer
def getResults():
    """ Summarize Results """
    lRate = 0
    if failed != 0:
        lRate = failed / (count) * 100
        lRate = "%.2f" % lRate
    print("\nTCP Ping Results: Connections (Total/Pass/Fail): [{:}/{:}/{:}] (Failed: {:}%)".format((count), passed, failed, str(lRate)))
def signal_handler(signal, frame):
    getResults()
    sys.exit(0)

count = 0
host = 'ipv6.google.com'
port = 80
maxCount = 1
# Pass/Fail counters
passed = 0
failed = 0
# Register SIGINT Handler
signal.signal(signal.SIGINT, signal_handler)
# Loop while less than max count or until Ctrl-C caught
while count < maxCount:
    # Increment Counter
    count += 1
    success = False
    # New Socket
    s = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)
    # 1sec Timeout
    s.settimeout(1)
    # Start a timer
    s_start = timer()
    # Try to Connect
    try:
        s.connect((host, int(port)))
        s.shutdown(socket.SHUT_RD)
        success = True
    # Connection Timed Out
    except socket.timeout:
        print("Connection timed out!")
        failed += 1
    except OSError as e:
        print("OS Error:", e)
        failed += 1
    # Stop Timer
    s_stop = timer()
    s_runtime = "%.2f" % (1000 * (s_stop - s_start))
    if success:
        print("Connected to %s[%s]: tcp_seq=%s time=%s ms" % (host, port, (count-1), s_runtime))
        passed += 1
    # Sleep for 1sec
    if count < maxCount:
        time.sleep(1)
# Output Results if maxCount reached
getResults()

我得到的错误:

OS Error: [Errno -2] Name or service not known
TCP Ping Results: Connections (Total/Pass/Fail): [1/0/1] (Failed: 100.00%)

socket.AF_INET 代表 IPv4 套接字。要使用 IPv6:

s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

按照上述方式修改代码后,您将获得:

Connected to ipv6.google.com[80]: tcp_seq=0 time=32.61 ms

TCP Ping Results: Connections (Total/Pass/Fail): [1/1/0] (Failed: 0%)