C#實現Ping服務器


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("請輸入IP:");
            var ip = Console.ReadLine();
            var resutl = Ping(ip);
            Console.WriteLine(resutl);
            Console.ReadLine();
        }

        /// <summary>  
        /// 是否能 Ping 通指定的主機  
        /// </summary>  
        /// <param name="ip">ip 地址或主機名或域名</param>  
        /// <returns>true 通,false 不通</returns>  
        static bool Ping(string ip)
        {
            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 = 5000; // Timeout 時間,單位:毫秒  
                System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
                if (reply == null || reply.Status == System.Net.NetworkInformation.IPStatus.Success)
                    return true;

                return false;
            }
            catch (System.Net.NetworkInformation.PingException e)
            {
                throw new Exception("找不到服務器");
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM