如何使用 JavaScript ping IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4954741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to ping IP addresses using JavaScript
提问by user434885
I want to run a JavaScript code to ping 4 different IP addresses and then retrieve the packet loss and latency of these ping requests and display them on the page.
我想运行一个 JavaScript 代码来 ping 4 个不同的 IP 地址,然后检索这些 ping 请求的丢包和延迟并将它们显示在页面上。
How do I do this?
我该怎么做呢?
回答by Piskvor left the building
You can't do this from JS. What you could do is this:
你不能从 JS 中做到这一点。你可以做的是:
client --AJAX-- yourserver --ICMP ping-- targetservers
Make an AJAX request to your server, which will then ping the target servers for you, and return the result in the AJAX result.
向您的服务器发出 AJAX 请求,然后服务器将为您 ping 目标服务器,并在 AJAX 结果中返回结果。
Possible caveats:
可能的警告:
- this tells you whether the target servers are pingable from your server, not from the user's client
- so the client won't be able to test hosts its LAN
- but you shouldn't let the host check hosts on the server's internal network, if any exist
- some hosts may block traffic from certain hosts and not others
- you need to limit the ping count per machine:
- to avoid the AJAX request from timing out
- some site operators can get very upset when you keep pinging their sites all the time
- resources
- long-running HTTP requests could run into maximum connection limit of your server, check how high it is
- many users trying to ping at once might generate suspicious-looking traffic (all ICMP and nothing else)
- concurrency - you may wish to pool/cache the up/down status for a few seconds at least, so that multiple clients wishing to ping the same target won't launch a flood of pings
- 这告诉你目标服务器是否可以从你的服务器 ping 通,而不是从用户的客户端
- 因此客户端将无法测试其 LAN 主机
- 但是您不应该让主机检查服务器内部网络上的主机(如果存在)
- 某些主机可能会阻止来自某些主机而不是其他主机的流量
- 您需要限制每台机器的 ping 计数:
- 避免 AJAX 请求超时
- 当您一直 ping 他们的网站时,某些网站运营商可能会非常沮丧
- 资源
- 长时间运行的 HTTP 请求可能会遇到服务器的最大连接限制,请检查它有多高
- 许多试图同时 ping 的用户可能会产生可疑的流量(所有 ICMP 和其他任何内容)
- 并发 - 您可能希望至少将 up/down 状态集中/缓存几秒钟,以便希望 ping 同一个目标的多个客户端不会启动大量 ping
回答by Dennis G
The only method I can think of is loading e.g. an image file from the external server. When that load fails, you "know" the server isn't responding (you actually don't know, because the server could just be blocking you).
我能想到的唯一方法是从外部服务器加载例如图像文件。当加载失败时,您“知道”服务器没有响应(您实际上不知道,因为服务器可能只是阻止了您)。
Take a look at this example code to see what I mean:
看看这个示例代码,看看我的意思:
/*note that this is not an ICMP ping - but a simple HTTP request
giving you an idea what you could do . In this simple implementation it has flaws
as Piskvor correctly points out below */
function ping(extServer){
var ImageObject = new Image();
ImageObject.src = "http://"+extServer+"/URL/to-a-known-image.jpg"; //e.g. logo -- mind the caching, maybe use a dynamic querystring
if(ImageObject.height>0){
alert("Ping worked!");
} else {
alert("Ping failed :(");
}
}
回答by Gwen Wing
I was inspired by the latest comment, so I wrote this quick piece of code.
我受到了最新评论的启发,所以我写了这段简短的代码。
This is a kind of "HTTP ping" which I think can be quite useful to use along with XMLHttpRequest calls(), for instance to figure out which is the fastest server to use in some case or to collect some rough statistics from the user's internet connexion speed.
这是一种“HTTP ping”,我认为与 XMLHttpRequest 调用()一起使用非常有用,例如找出在某些情况下使用哪个服务器最快或从用户的互联网收集一些粗略的统计数据连接速度。
This small function is just connecting to an HTTP server on an non-existing URL (that is expected to return a 404), then is measuring the time until the server is answering to the HTTP request, and is doing an average on the cumulated time and the number of iterations.
这个小函数只是在不存在的 URL 上连接到 HTTP 服务器(预计会返回 404),然后测量直到服务器响应 HTTP 请求的时间,并对累计时间进行平均和迭代次数。
The requested URL is modified randomely at each call since I've noticed that (probably) some transparent proxies or caching mechanisms where faking results in some cases, giving extra fast answers (faster than ICMP actually which somewhat weird).
请求的 URL 在每次调用时都会随机修改,因为我注意到(可能)一些透明代理或缓存机制在某些情况下会导致伪造,从而提供额外的快速答案(实际上比 ICMP 快,这有点奇怪)。
Beware to use FQDNs that fit a real HTTP server! Results will display to a body element with id "result", for instance:
请注意使用适合真实 HTTP 服务器的 FQDN!结果将显示到 ID 为“result”的 body 元素,例如:
<div id="result"></div>
Function code:
功能代码:
function http_ping(fqdn) {
var NB_ITERATIONS = 4; // number of loop iterations
var MAX_ITERATIONS = 5; // beware: the number of simultaneous XMLHttpRequest is limited by the browser!
var TIME_PERIOD = 1000; // 1000 ms between each ping
var i = 0;
var over_flag = 0;
var time_cumul = 0;
var REQUEST_TIMEOUT = 9000;
var TIMEOUT_ERROR = 0;
document.getElementById('result').innerHTML = "HTTP ping for " + fqdn + "</br>";
var ping_loop = setInterval(function() {
// let's change non-existent URL each time to avoid possible side effect with web proxy-cache software on the line
url = "http://" + fqdn + "/a30Fkezt_77" + Math.random().toString(36).substring(7);
if (i < MAX_ITERATIONS) {
var ping = new XMLHttpRequest();
i++;
ping.seq = i;
over_flag++;
ping.date1 = Date.now();
ping.timeout = REQUEST_TIMEOUT; // it could happen that the request takes a very long time
ping.onreadystatechange = function() { // the request has returned something, let's log it (starting after the first one)
if (ping.readyState == 4 && TIMEOUT_ERROR == 0) {
over_flag--;
if (ping.seq > 1) {
delta_time = Date.now() - ping.date1;
time_cumul += delta_time;
document.getElementById('result').innerHTML += "</br>http_seq=" + (ping.seq-1) + " time=" + delta_time + " ms</br>";
}
}
}
ping.ontimeout = function() {
TIMEOUT_ERROR = 1;
}
ping.open("GET", url, true);
ping.send();
}
if ((i > NB_ITERATIONS) && (over_flag < 1)) { // all requests are passed and have returned
clearInterval(ping_loop);
var avg_time = Math.round(time_cumul / (i - 1));
document.getElementById('result').innerHTML += "</br> Average ping latency on " + (i-1) + " iterations: " + avg_time + "ms </br>";
}
if (TIMEOUT_ERROR == 1) { // timeout: data cannot be accurate
clearInterval(ping_loop);
document.getElementById('result').innerHTML += "<br/> THERE WAS A TIMEOUT ERROR <br/>";
return;
}
}, TIME_PERIOD);
}
For instance, launch with:
例如,启动:
fp = new http_ping("www.linux.com.au");
Note that I couldn't find a simple corelation between result figures from this script and the ICMP ping on the corresponding same servers, though HTTP response time seems to be roughly-exponential from ICMP response time. This may be explained by the amount of data that is transfered through the HTTP request which can vary depending on the web server flavour and configuration, obviously the speed of the server itself and probably other reasons.
请注意,虽然 HTTP 响应时间似乎与 ICMP 响应时间大致呈指数关系,但我无法在该脚本的结果数字与相应相同服务器上的 ICMP ping 之间找到简单的相关性。这可能是由于通过 HTTP 请求传输的数据量可能会因 Web 服务器的风格和配置而异,显然是服务器本身的速度以及可能的其他原因。
This is not very good code but I thought it could help and possibly inspire others.
这不是很好的代码,但我认为它可以帮助并可能启发他人。
回答by Dinesh
function ping(url){
new Image().src=url
}
Above pings the given Url.
Generally used for counters / analytics.
It won't encounter failed responses to client(javascript)
以上 ping 给定的 Url。
通常用于计数器/分析。
它不会遇到对客户端的失败响应(javascript)
回答by Securis
The closest you're going to get to a ping in JS is using AJAX, and retrieving the readystates, status, and headers. Something like this:
在 JS 中最接近 ping 的方法是使用 AJAX,并检索就绪状态、状态和标头。像这样的东西:
url = "<whatever you want to ping>"
ping = new XMLHttpRequest();
ping.onreadystatechange = function(){
document.body.innerHTML += "</br>" + ping.readyState;
if(ping.readyState == 4){
if(ping.status == 200){
result = ping.getAllResponseHeaders();
document.body.innerHTML += "</br>" + result + "</br>";
}
}
}
ping.open("GET", url, true);
ping.send();
Of course you can also put conditions in for different http statuses, and make the output display however you want with descriptions etc, to make it look nicer. More of an http url status checker than a ping, but same idea really. You can always loop it a few times to make it feel more like a ping for you too :)
当然,您也可以为不同的 http 状态设置条件,并根据需要使用描述等来显示输出,以使其看起来更好。比 ping 更像是 http url 状态检查器,但实际上是相同的想法。你总是可以循环几次,让它感觉更像是对你的 ping :)
回答by Jeffrey Tackett
Is it possible to ping a server from Javascript?
Should check out the above solution. Pretty slick.
应该检查上面的解决方案。很圆滑。
Not mine, obviously, but wanted to make that clear.
显然不是我的,但我想说清楚。
回答by PLA
You can't PING with Javascript. I created Java servlet that returns a 10x10 pixel green image if alive and a red image if dead. https://github.com/pla1/Misc/blob/master/README.md
您无法使用 Javascript 进行 PING。我创建了 Java servlet,如果活着返回一个 10x10 像素的绿色图像,如果死亡则返回一个红色图像。https://github.com/pla1/Misc/blob/master/README.md