以下是C#代码,可以直接复制使用。
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace PingMock
{
class MockerClass
{
private static Object thisobject = new Object();
public void Ping(string Host)
{
//string rtn = "";
ManagementObjectSearcher mos = null;
ManagementObjectCollection moc = null;
LogClass writeLog = new LogClass();
try
{
string searchString = "select * from win32_PingStatus where Address = '" + Host.Trim() + "'";
mos = new ManagementObjectSearcher(searchString);
moc = mos.Get();
foreach (ManagementObject mo in moc)
{
object obj = mo.Properties["StatusCode"].Value;
if (obj == null)
{
lock (thisobject)
{
writeLog.WriteLogFile(Host + " PING 执行失败。可能是主机未知。");
}
//return Host+" PING 执行失败。可能是主机未知。";
}
else
{
if (obj.ToString().Trim() == "0")
{
//rtn = "OK";
break;
}
lock (thisobject)
{
writeLog.WriteLogFile(Host + " PING 不通!");
}
}
}
}
catch (Exception ex)
{
writeLog.WriteLogFile(Host + " PING 不通,可能原因为:" + ex.Message);
//rtn = Host+" PING 不通,可能原因为:"+ ex.Message;
}
finally
{
if (moc != null) moc.Dispose();
if (mos != null) mos.Dispose();
}
//return rtn;
}
}
}
可以修改城自己需要的形式。我这个是不返回结果,直接记录日志中。