[英]C# Check Remote Server
如果有遠程服務器,有人可以建議檢查(使用.NET 3.5)的最佳方法嗎?
我正在考慮使用以下代碼,但想知道如果社區有另一種選擇,是否存在更好的方法。
TcpClient client = new TcpClient("MyServer", 80);
if (!client.Connected)
{
throw new Exception("Unable to connect to MyServer on Port 80");
}
client.Close();
如果您只是想查看給定服務器是否在線,那么在大多數情況下,簡單的ping應該可以完成工作。
PingReply pingReply;
using (var ping = new Ping())
pingReply = ping.Send("http://www.stackoverflow.com/");
var available = pingReply.Status == IPStatus.Success;
使用此方法,您也不會以任何方式濫用HTTP服務器。
否則(如果你想檢查特定端口上是否可以連接),那基本上看起來很好。
只是為了添加丹的答案......我只需要實現這個,這里有一個很好的小代碼片段,可以幫助那些從谷歌這里制作它的人。
Imports System.Net
Private Function URLExists(pURL As String) As Boolean
Try
'Creating the HttpWebRequest
Dim request As HttpWebRequest = TryCast(WebRequest.Create(pURL), HttpWebRequest)
'Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD"
'Getting the Web Response.
Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
'Returns TURE if the Status code == 200
Return (response.StatusCode = HttpStatusCode.OK)
Catch
'Any exception will returns false.
Return False
End Try
End Function
抱歉這是VB,但這就是我面前的情況。 我將把它作為練習讓讀者根據需要將其轉換為C#。
如果您使用的是以前版本的.NET Framework,就像我一樣,版本2,您將沒有Ping,也沒有System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
。 然后,您可以使用HttpWebRequest
檢查主機的異常:
public static bool AccessToWebService()
{
string host = "http://192.168.99.41";
try
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(host);
request.Method = "HEAD";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
catch (Exception)
{
return false;
}
}
我猜你想檢查一下網站是否可用。 您可以使用System.Net.WebRequest
並檢查結果。
更新:根據您的評論,如果您有一些服務器(和服務)要監控,那么使用Nagios , HostMonitor或IPSentry等軟件包可能更好,而不是自己滾動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.