核心代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Text;
//....
//arg为主机IP,timeout为连接超时的时间,packSize为封包的大小
private string PingHost(string arg, int timeout, int packSize)
{
string data=MakeString(packSize);
Ping pingSender = new Ping ();
byte[] buffer = Encoding.ASCII.GetBytes (data);
PingReply reply = pingSender.Send(arg, timeout, buffer);
if (reply.Status == IPStatus.Success)
{
string hInfo = "";
hInfo +="回复源:"+ reply.Address.ToString();
hInfo +="/n 用时:" + (reply.RoundtripTime).ToString() + " ms";
hInfo +="/n 接收到:" + (reply.Buffer.Length).ToString() + " Byte";
return hInfo;
}
else return "连接主机失败";
}
private string MakeString(int Length)
{
string baseString ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int len = baseString.Length;
Random rnd = new Random();
StringBuilder result = new StringBuilder();
for(int i=0; i<Length; i++)
{
result.Append(baseString.Substring(rnd.Next(len),1));
}
return result.ToString();
}
//调用PingHost方法就可以
//我是在.NET Framework 3.5调试的