如何检查c#中是否有第三台服务器连接了两台服务器? 我在服务器A,我想知道服务器B和服务器C是否已连接。 我只有代码来检查我是否连接到服务器B或C. 我有什么:
public bool AreConnected(string ip)
{
bool connected= false;
Ping p = new Ping();
try
{
PingReply reply = p.Send(ip);
connected = reply.Status == IPStatus.Success;
}
catch (PingException)
{
// Discard PingExceptions and return false;
}
return connected;
}
答案 0 :(得分:2)
这可能不是最好的方法,它需要机器B上的管理员权限,但它可以工作。
使用PsExec。此工具允许您在远程计算机上运行命令。
创建一个命令行程序,将ip地址作为命令行参数,ping IP地址并输出结果。
然后运行PsExec(来自C#代码)在机器B上执行这样的程序并收集结果(也来自代码)。
您需要使用Process.Start才能从C#代码执行PsExec命令。
答案 1 :(得分:0)
我使用PsExec并且工作正常,在我的代码下面可能可以帮助其他人,
public bool IsPingable(string servA, string servB)
{
string path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\Resources\\PsExec.exe";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = path;
p.StartInfo.Arguments = @"\\" + servA + " ping " + servB + " -n 1";
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
if (!output.Contains("100% loss"))
{
return true;
}
else
{
return false;
}
}