0

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

4

2 回答 2

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.XY 范围内 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);
    }
}
于 2014-07-15T12:37:04.380 回答
1

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

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

您有两种选择:

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