For循环不适合该函数

时间:2014-07-15 12:31:54

标签: javascript for-loop port-scanning

这是一个for循环包含一个函数,它通过使用checkPort函数指定端口是打开还是关闭。

var IPAdress = '192.168'; //Local area network to scan (this is rough)
var Portadd = 80; 
var Newip;
var i=0;
var j=0;
//scan over a range of IP addresses and execute a function each time the port is shown to be open.
for(i=0; i <= 1; i++){
for(j=0; j <= 3; j++){
Newip = IPAdress+'.'+i+'.'+j;

checkPort(Portadd, Newip, function(error, status, host, port) {
// Status should be 'open' since the HTTP server is listening on that port
if(status == "open"){
        console.log("IP" , Newip, "on port" , Portadd, "is open");
    }
else if(status == "closed"){
        console.log("IP" , Newip, "on port" , Portadd, "is closed");
    }
});

console.log(Newip);
}
}

这就是结果:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
IP 192.168.1.3 on port 80 is closed
IP 192.168.1.3 on port 80 is closed
IP 192.168.1.3 on port 80 is closed
IP 192.168.1.3 on port 80 is closed
IP 192.168.1.3 on port 80 is closed
IP 192.168.1.3 on port 80 is closed
IP 192.168.1.3 on port 80 is closed
IP 192.168.1.3 on port 80 is closed

因为打印出的NewIp工作正常,我预计结果会是这样的:

IP 192.168.0.0 on port 80 is closed
IP 192.168.0.1 on port 80 is closed
IP 192.168.0.2 on port 80 is closed
IP 192.168.0.3 on port 80 is closed
IP 192.168.1.0 on port 80 is closed
IP 192.168.1.1 on port 80 is closed
IP 192.168.1.2 on port 80 is closed
IP 192.168.1.3 on port 80 is closed

有没有人知道为什么它会在实际结果部分显示类似的IP?

2 个答案:

答案 0 :(得分:1)

更改为:

checkPort(Portadd, Newip, function(error, status, host, port) {
    // Status should be 'open' since the HTTP server is listening on that port
    if(status == "open"){
            console.log("IP" , host, "on port" , port, "is open");
    }
    else if(status == "closed"){
            console.log("IP" , host, "on port" , port, "is closed");
    }
});

您无法将“parrent”变量传递给回调函数,尤其是您有hostport输入参数。

在[0,1,2]中的X和[0,1,2,3,4]中的Y的范围192.168.X.Y中的ip地址的完整示例:

var IPAdress = '192.168'; //Local area network to scan (this is rough)
var Portadd = 80; 
var i=0;
var j=0;

//scan over a range of IP addresses and execute a function each time the port is shown to be open.
for(i=0; i <= 2; i++){
    for(j=0; j <= 4; j++){
        var Newip = IPAdress + '.' + i + '.' + j;

        checkPort(Portadd, Newip, function(error, status, host, port) {
            // Status should be 'open' since the HTTP server is listening on that port
            if(status == "open"){
                console.log("IP" , host, "on port" , port, "is open");
            }else if(status == "closed"){
                console.log("IP" , host, "on port" , port, "is closed");
            }
        });

        console.log(Newip);
    }
}

答案 1 :(得分:1)

checkPort正在使用稍后执行的回调函数,并且在执行它时,变量NewIP中的所有IP地址都已更改。

结果是回调函数打印了NewIP的最后一个值,因为它引用了该值。

您有两种选择:

  • 您可以使用传递给回调函数的参数host
  • 通过更改var NewIP在内部for循环中定义var Newip = IPAdress+'.'+i+'.'+j;。这将创建一个范围为回调函数的变量。