使用python对ipv6网站进行tcp ping

时间:2019-02-13 13:02:44

标签: python python-3.x sys python-sockets

我是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%)

1 个答案:

答案 0 :(得分:1)

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%)