C#-如何ping IP

来源:互联网 发布:java富有创意的小程序 编辑:程序博客网 时间:2024/05/13 13:42

C#-如何ping IP

dll:// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.dll

///
/// 是否能 Ping 通指定的主机
///
/// ip 地址或主机名或域名
/// true 通,false 不通
private bool Ping(string ip)
{
bool w_blnReturn = false;
try
{

    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)        w_blnReturn = true;    else        w_blnReturn = false;}catch (Exception ex){    //异常日志    msg = String.Format("Ping执行异常,详细:{0}", ex.StackTrace.ToString());    log.Error(msg);}return w_blnReturn;

}
  

方法2: PingReply reply = pinSender.Send(str_ip, timeout, buffer, options);

///
/// Ping固定IP
///
/// IP地址
/// 成功返回1,失败返回0
public int CheckDeviceStatus(string str_ip)
{
Ping pinSender = new Ping();
PingOptions options = new PingOptions();
string data = “”;
byte[] buffer = Encoding.ASCII.GetBytes(data);
options.DontFragment = true;
int timeout = 1200;
PingReply reply = pinSender.Send(str_ip, timeout, buffer, options);
if (reply.Status != IPStatus.Success)
{
return 0;
}

return 1;

}
  

0 0
原创粉丝点击