C#代码实现检测是否能ping通某台服务器

C#代码实现检测是否能ping通某台服务器

背景

在很多业务场景下都需要根据网络状态执行不同的操作,而最常用和效率比较高的办法就是使用ping,那么在C#代码中如何实现这块逻辑呢?

代码实现

编写一个工具类TPTools.cs,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;

namespace WindowsFormsApplication1
{
    public class IPTools
    {
        #region 检测某个IP或域名是否可以Ping通

        /// <summary>
        /// 检测某个IP或域名是否可以Ping通
        /// </summary>
        /// <param name="strIpOrDName">IP或域名</param>
        /// <returns>true为通,false为不通</returns>
        public static bool PingIpOrDomainName(string strIpOrDName)
        {
            try
            {
                Ping objPingSender = new Ping();
                PingOptions objPinOptions = new PingOptions();
                objPinOptions.DontFragment = true;
                string data = "";
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                int intTimeout = 120;
                PingReply objPinReply = objPingSender.Send(strIpOrDName, intTimeout, buffer, objPinOptions);
                string strInfo = objPinReply.Status.ToString();
                if (strInfo == "Success")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion
    }
}

测试代码

private void button1_Click(object sender, EventArgs e)
{
    string ip1 = "127.0.0.1";
    bool result = IPTools.PingIpOrDomainName(ip1);
    Console.WriteLine("ping {0} result is {1}!", ip1, result);

    string ip2 = "www.baidu.com";
    result = IPTools.PingIpOrDomainName(ip2);
    Console.WriteLine("ping {0} result is {1}!", ip2, result);

    string ip3 = "192.168.5.123";
    result = IPTools.PingIpOrDomainName(ip3);
    Console.WriteLine("ping {0} result is {1}!", ip3, result);
}

运行结果

运行结果如下图:
在这里插入图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页