How to check whether a port is open at client's network/firewall?

前端 未结 8 1418
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 13:13

This is solved at last with \"timeout\" attribute of jQuery AJAX (and JSONP). See my own answer !

Please see the updated part, I

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 13:38

    In JavaScript, you have to work-around the asynchronous issue. Here is a proposal:

    • The HTML page displays an animated image as a progress bar
    • You invoke the checkURL
    • After either receiving the callback or a defined timeout, you change display for an error message or do on with the job to do

    Based on the following document with the use of XMLHttpRequest, here is a code example for checkURL:

    var myrequest = new ajaxRequest();
    var isAccessible = false;
    myrequest._timeout = setTimeout(function() {
          myrequest.abort();
          displayErrorMessage();
        },
        1000
        ) //end setTimeout
    myrequest.onreadystatechange = function() {
        if (myrequest.readyState == 4) { //if request has completed
          if (myrequest.status == 200) {
            isAccessible = false;
            goOnWithTheJob();
          } else {
            displayErrorMessage();
          }
        }
    myrequest.open("GET", url, true);
    myrequest.send(null); //send GET request
    // do nothing - wait for either timeout or readystate callback 
    

    This code lets 1 second to get the 200 response from a HTTP GET on a basic resource.

    In your local test, you get an immediate answer because the system answers connection reset if the port is closed but a firewall just does not answer.

    Even if the open method may be used synchronously, I recommend the use of a timer because the code is likely to wait for TCP timeouts and retries (3 x 1 minute ?) as a firewall usually just drops packets on closed ports and may reject ICMP packets, preventing you to test availability thanks to ping. And I imagine such a long wait is not expected for such a check.

提交回复
热议问题