2011-04-20 69 views
5

如何確定某個IP地址是否可以連接?如何確定主機是否可達?

我需要編寫一個小node.js樣本而tryes連接到ip:port並返回truefalse,從而確定,如果主機是可到達與否。

回答

16

http.get

var options = { 
    host: 'www.google.com', 
    port: 80, 
    path: '/index.html' 
}; 

http.get(options, function(res) { 
    if (res.statusCode == 200) { 
    console.log("success"); 
    } 
}).on('error', function(e) { 
    console.log("Got error: " + e.message); 
}); 

function testPort(port, host, cb) { 
    http.get({ 
    host: host, 
    port: port 
    }, function(res) { 
    cb("success", res); 
    }).on("error", function(e) { 
    cb("failure", e); 
    }); 
} 

對於TCP套接字只是使用net.createConnection

function testPort(port, host, cb) { 
    net.createConnection(port, host).on("connect", function(e) { 
    cb("success", e); 
    }).on("error", function(e) { 
    cb("failure", e); 
    }); 
} 
+0

您的解決方案適用於HTTP服務器的互聯,但我需要驗證是否可以與某個主機建立TCP連接。 – George 2011-04-20 16:03:53

+0

@George然後只需打開一個tcp端口。我將編輯答案 – Raynos 2011-04-20 16:11:19

+0

10x以便及時回答。這正是我需要的 - 建立一個tcp連接 – George 2011-04-21 08:13:20

-2

如果只是HTTP你有興趣,你可以使用HTTP HEAD請求(而不是POST/GET):

function hostAvailable(url) { 
    var req = new XMLHttpRequest(); 
    req.open('HEAD', url, false); 
    req.send(); 
    return req.status!=404; 
} 
+3

這不是有效的node.js代碼。 – Raynos 2011-04-20 15:32:17