简体   繁体   中英

Check if connection to IP address is lost

For my web app I need a way to detect whether the application has lost the connection to the IP address (100.100.100.100) it runs on or whether the device has connected to a different network/connection. This must all be done client side. Currently I am doing the following but it doesn't seem to work. Any ideas how to accomplish this? Thanks.

$.ajax({
   type: "GET",
   url: "100.100.100.100",
   success: function(){
    alert("Connection Good!")
   }
   error: function(XMLHttpRequest, textStatus, errorThrown){
    if(textStatus == 'timeout') {
       alert("Connection has been lost.");  
    }
   }
});

It's not going to work to a random IP address due to the same-origin policy. The best the thing to do is to have a request to a URL on the server your app is served from (ie same Authority as the JS file comes from) which gives a known good response.

** Update Just to be clear, by 'Authority' I really mean host, port, and protocol. So for example, http://google.com is not the same as https://google.com nor is it the same as http://google.com:8080

You can create simple PHP (or whatever language you are using) which actually pings the target IP.

Then you can call

http://www.example.com/my_ping_script.php?target=10.10.10.10

through AJAX and it will return the connection status as simple "OK" or "LOST".

By ping I mean ICMP ping

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