简体   繁体   中英

tcp ping for ipv6 websites using python

I am new to python. I want to ping IPv6 websites via TCP. The below code pings on IPv4 websites successfully. but it fails for IPv6 websites. I need to ping IPv6 websites also.

Is there any possible solutions to ping ipv6 websites via TCP.

Here's the code:

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

The error i got:

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 stands for IPv4 sockets. To use IPv6 ones:

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

With your code modified as above will, you'll get:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM