如何在客户端JavaScript中检查端口可用性?

时间:2012-03-27 07:16:06

标签: javascript port firewall

是否可以在JavaScript中(在浏览器中)检测防火墙或路由器是否禁用了端口?

3 个答案:

答案 0 :(得分:5)

不,使用纯javascript这是不可能的(除了向特定端口发出http请求,但这些结果意味着很少),但你可以做的是从外面检查(换句话说你的服务器)是否具体港口是开放的。另一个选择是使用一个java applet或浏览器插件,如果你真的需要它可以为你做这个,在这种情况下有各种开源工具,如果你有必要的话可以移植它们与那些经验。请注意,这并不完全是用户友好的。 (无论哪种方式,如果你想描述你需要它的确切场景会很有用,因为可能存在一个完全不同的解决方案。)

答案 1 :(得分:4)

您只能看到预期的响应是否存在。

使用javascript时,必须留在HTTP的边界。

当然,您可以在任何服务器端口发送Ajax请求,看看是否收到错误。如果你想检查当前机器的端口,那么可能在“localhost:843”上发送请求可能有所帮助。

但错误可能是其他一些原因,而不一定是防火墙问题。

我们需要更多信息来帮助您。

答案 2 :(得分:3)

如果您足够灵活以使用jQuery,请参阅此Answer by me。这不仅会检查端口的可用性,还会检查成功响应代码200是来自远程(或任何,我的意思是它也支持跨域)服务器。同样在这里给出解决方案。我将在这里查看843号港口。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <script type="text/javascript" src="jquery-1.7.2-min.js"></script>
    </head>
    <body>
        <script type"text/javascript">
            var isAccessible = null;
            function checkConnection() {
  /*make sure you host a helloWorld HTML page in the following URL, so that requests are succeeded with 200 status code*/
                var url = "http://yourserverIP:843/test/hello.html" ; 
                $.ajax({
                    url: url,
                    type: "get",
                    cache: false,
                    dataType: 'jsonp', // it is for supporting crossdomain
                    crossDomain : true,
                    asynchronous : false,
                    jsonpCallback: 'deadCode',
                    timeout : 1500, // set a timeout in milliseconds
                    complete : function(xhr, responseText, thrownError) {
                        if(xhr.status == "200") {
                           isAccessible = true;
                           success(); // yes response came, execute success()
                        }
                        else {
                           isAccessible = false;
                           failure(); // this will be executed after the request gets timed out due to blockage of ports/connections/IPs
                        }
                    }
               });
            }
            $(document).ready( function() {
                checkConnection(); // here I invoke the checking function
            });
        </script>
    </body>
</html>
相关问题