这是一个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的内容?

最佳答案

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

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

您有两种选择:


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

09-19 04:39