如何ping服务器url/端口?

2024-03-28 17:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中通过url/端口ping服务器,并以毫秒(毫秒)为单位接收响应? 我正在绞尽脑汁,我使用了tcping,我正在研究套接字,但它似乎并不那么简单,有什么提示吗

pings_ookla_script_root-OK.py

#!/usr/bin/env python3

import requests
import os
import sys
import pings

p = pings.Ping(quiet=False)
port = 8080

response = p.ping('google.com', times=4)
print(response)

输出:

47 bytes from 142.250.78.206: icmp_seq=0 ttl=114 time=11.326 ms
47 bytes from 142.250.78.206: icmp_seq=1 ttl=114 time=11.059 ms
47 bytes from 142.250.78.206: icmp_seq=2 ttl=114 time=10.793 ms
47 bytes from 142.250.78.206: icmp_seq=3 ttl=114 time=11.213 ms
--- google.com ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max = 10.793/11.098/11.326 ms
{'max_rtt': 11.325597763061523, 'min_rtt': 10.793447494506836, 'avg_rtt': 11.09778881072998, 'packet_lost': None, 'ret_code': 0, 'packet_size': 47, 'timeout               ': 1000, 'dest': 'google.com', 'dest_ip': '142.250.78.206'}

Tags: fromimportrttcombytestimepacketresponse
1条回答
网友
1楼 · 发布于 2024-03-28 17:33:40

您不能ping端口,因为ping使用的是没有端口概念的ICMP。端口属于传输层协议,如TCP和UDP

如果要执行只能通过端口访问的web服务器测试,可以使用模块tcp\U延迟

tcp-latency provides an easy way to measure latency using TCP.
Inspired by other similar tools, tcp-latency comes from the need of running network diagnosis/troubleshooting tasks with Python on serverless infrastructure (as many providers don't include ping/ICMP support) but should work too in any other environment with Python>=36.
Features
Runs as a command-line tool or inside your code as a module. Custom parameters for a port, runs, timeout and wait time between runs. IPv4 (e.g 52.26.14.11) and domain (e.g google.com) host support. Human readable output when running as a command-line tool. No external dependencies. Small and extensible.

pip3 install tcp_latency
python3

现在您使用的是python环境

>>> from tcp_latency import measure_latency
>>> measure_latency(host='google.com')
[34.57]
>>> measure_latency(host='52.26.14.11', port=80, runs=10, timeout=2.5)
[433.82, 409.21, 409.25, 307.09, 306.64, 409.45, 306.58, 306.93, 409.25, 409.26]

其他支持:

如果你尝试在任何地方进行ping测试。我建议使用成熟的工具。 Ping测试结果包括国内和国际客户Ping结果。 通过谷歌搜索“全球ping测试”,排名第一的包括https://tools.keycdn.com/ping","https://www.dotcom-tools.com/ping-test“等等

相关问题 更多 >