'Calculating RTT using an IP address

Hi I am trying to find a way to calculate the round trip time for a specific IP using python. All i can find is using a url but thats not the way I would like it to work and so far no information was helpful

I only found this code:

import time 
import requests 
  
# Function to calculate the RTT 
def RTT(url): 
  
    # time when the signal is sent 
    t1 = time.time() 
  
    r = requests.get(url) 
  
    # time when acknowledgement of signal  
    # is received 
    t2 = time.time() 
  
    # total time taken 
    tim = str(t2-t1) 
  
    print("Time in seconds :" + tim) 
  
# driver program  
# url address 
url = "http://www.google.com"
RTT(url) 

Can anyone please tell me how I can adjust this code to take an IP address rather than a URL ? Thanks



Solution 1:[1]

A URL follows a specific format: protocol + subdomain + domain + path + filename. The domain portion of the URL is essentially a user-friendly ip address, meaning that the DNS will/can resolve it to an exact IP address. This should mean that we can replace the domain portion of our url with our Ip address/port and this code should work fine. Using the HTTP protocol with our local IP address, we would make the following changes:

url = "http://127.0.0.1"

Here we are using port 80, the default for the HTTP protocol, but we can add a custom port number to the url as well: url = "http://127.0.0.1:8000"

The other option would be to open a socket, send data and wait for a response. Here is an example using a TCP connection:

import time
import socket
def RTT(host="127.0.0.1", port=80, timeout=40):
    # Format our parameters into a tuple to be passed to the socket
    sock_params = (host, port)
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        # Set the timeout in the event that the host/port we are pinging doesn't send information back
        sock.settimeout(timeout)
        # Open a TCP Connection
        sock.connect(sock_params)
        # Time prior to sending 1 byte
        t1 = time.time()
        sock.sendall(b'1')
        data = sock.recv(1)
        # Time after receiving 1 byte
        t2 = time.time()
        # RTT
        return t2-t1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1