【问题标题】:Calculating RTT using an IP address使用 IP 地址计算 RTT
【发布时间】:2020-07-13 14:09:31
【问题描述】:

您好,我正在尝试找到一种方法来使用 python 计算特定 IP 的往返时间。 我所能找到的只是使用一个网址,但这不是我希望它工作的方式,到目前为止没有任何信息有用

我只找到了这段代码:

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) 

谁能告诉我如何调整此代码以获取 IP 地址而不是 URL? 谢谢

【问题讨论】:

  • 什么是 url 而不是 DNS 映射到 IP 地址?你试过像url="http://ipaddress:port"这样的东西吗?或者,打开一个套接字连接,发送消息/请求并等待响应
  • 您好,我不想使用主机名。我想通过 python 脚本使用其特定 ip 定位设备

标签: python ip-address roundtrip


【解决方案1】:

URL 遵循特定格式:协议 + 子域 + 域 + 路径 + 文件名。 URL 的域部分本质上是一个用户友好的 IP 地址,这意味着 DNS 将/可以将其解析为确切的 IP 地址。这应该意味着我们可以用我们的 IP 地址/端口替换我们 url 的域部分,并且这段代码应该可以正常工作。使用带有本地 IP 地址的 HTTP 协议,我们将进行以下更改:

url = "http://127.0.0.1"

这里我们使用的是 HTTP 协议的默认端口 80,但我们也可以在 url 中添加自定义端口号:url = "http://127.0.0.1:8000"

另一种选择是打开一个套接字,发送数据并等待响应。下面是一个使用 TCP 连接的例子:

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

【讨论】:

  • 这可以用 python 完成吗?只是为了获取特定设备(例如手机)的特定往返时间?
猜你喜欢
  • 2015-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
相关资源
最近更新 更多