代码改变世界

C#,测试网络是否通

2017-08-04 12:50  伟大的程序员2  阅读(466)  评论(0)    收藏  举报

public static bool Ping(string ip)
{
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
options.DontFragment = true;
string data = "Test Data!";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1000; // Timeout 时间,单位:毫秒
System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
{
return true;
}
else
{
return false;
}
}