当前位置: 首页>>代码示例>>C#>>正文


C# NetworkInformation.Ping类代码示例

本文整理汇总了C#中System.Net.NetworkInformation.Ping的典型用法代码示例。如果您正苦于以下问题:C# Ping类的具体用法?C# Ping怎么用?C# Ping使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Ping类属于System.Net.NetworkInformation命名空间,在下文中一共展示了Ping类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ListAllHosts

        public static void ListAllHosts(byte[] ipBase, Action<AddressStruct> itemCallback)
        {
            for (int b4 = 0; b4 <= 255; b4++)
            {
                var ip = ipBase[0] + "." + ipBase[1] + "." + ipBase[2] + "." + b4;

                var ping = new Ping();
                ping.PingCompleted += (o, e) =>
                {
                    if (e.Error == null && e.Reply.Status == IPStatus.Success)
                        if (itemCallback != null)
                        {
                            GetMacAddress(
                                e.Reply.Address,
                                (mac) =>
                                {
                                    itemCallback(new AddressStruct()
                                    {
                                        IPAddress = e.Reply.Address,
                                        MacAddress = mac
                                    });
                                });
                        }
                };
                ping.SendAsync(ip, null);
            }
        }
开发者ID:noant,项目名称:Pyrite,代码行数:27,代码来源:LANHelper.cs

示例2: pingHost

        public void pingHost(string hostName, int pingCount)
        {
            if (pingCount == 0)
            {
                pingCount = 43200;
            }
            Console.WriteLine("Host, Response Time, Status, Time ");
            String fileName = String.Format(@"tping-{0}-{1}-{2}-{3}.csv", DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            for (int i = 0; i < pingCount; i++)
            {
                Ping ping = new Ping();
                StreamWriter processedData = new StreamWriter(@fileName, true);
                try
                {
                    PingReply pingReply = ping.Send(hostName);

                    processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status);
                    processedData.Close();
                    Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status);

                }
                catch (System.Net.NetworkInformation.PingException)
                {
                    processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error");
                    Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error");
                    processedData.Close();
                    //Console.WriteLine(Ex);
                    //Environment.Exit(0);
                }
                Thread.Sleep(2000);
            }
            Console.WriteLine("\n" + "tping complete - {0} pings logged in {1}", pingCount, fileName);
        }
开发者ID:ingram1987,项目名称:tping,代码行数:33,代码来源:Program.cs

示例3: TestConnection

 public static bool TestConnection(string smtpServerAddress, int port)
 {
     Ping pingSender = new Ping();
     PingOptions options = new PingOptions();
     options.DontFragment = true;
     PingReply reply = null;
     try
     {
         reply = pingSender.Send(smtpServerAddress, 12000, Encoding.ASCII.GetBytes("SHIT"), options);
     }
     catch (System.Net.NetworkInformation.PingException)
     {
         return false;
     }
     if (reply.Status == IPStatus.Success)
     {
         IPHostEntry hostEntry = Dns.GetHostEntry(smtpServerAddress);
         IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port);
         using (Socket tcpSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
         {
             tcpSocket.Connect(endPoint);
             if (!CheckResponse(tcpSocket, 220))
                 return false;
             SendData(tcpSocket, string.Format("HELO {0}\r\n", Dns.GetHostName()));
             if (!CheckResponse(tcpSocket, 250))
                 return false;
             return true;
         }
     }
     else
         return false;
 }
开发者ID:RenzoBit,项目名称:SIGRE,代码行数:32,代码来源:Correo.cs

示例4: ReadAndPing

        public void ReadAndPing(string path)
        {
            File.OpenRead(path);
            ConsoleKeyInfo btn;

               do // Начала цикла
               {
                string ip = File.ReadLines(path);
                while (true) //читаем в ip строки из файла в path
                {
                    //Console.WriteLine(ip);
                    Ping pingSender = new Ping();
                    PingOptions options = new PingOptions();

                    options.Ttl = 60; //Продолжительность жизни пакета в секундах
                    int timeout = 120; //Таймаут выводется в ответе reply.RoundtripTime
                    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //Строка длиной 32 байта
                    byte[] buffer = Encoding.ASCII.GetBytes(data); //Преобразование строки в байты, выводится reply.Buffer.Length

                    PingReply reply = pingSender.Send(ip, timeout, buffer, options);

                    Console.WriteLine("Сервер: {0} Время={1} TTL={2}", reply.Address.ToString(), reply.RoundtripTime, reply.Options.Ttl); //Выводим всё на консоль

                    //ConsoleKeyInfo btn = Console.ReadKey(); //Создаём переменную которая хранит метод Описывающий нажатую клавишу консоли
                    //if (btn.Key == ConsoleKey.Escape) break;

                }

                //  ConsoleKeyInfo btn = Console.ReadKey(); //Создаём переменную которая хранит метод Описывающий нажатую клавишу консоли
                //  if (btn.Key == ConsoleKey.Escape) break;
            btn = Console.ReadKey(); //Переенная для чтения нажатия клавиши
            }
            while (btn.Key == ConsoleKey.Escape); //Чтение нажатия клавиши.
        }
开发者ID:Kubig,项目名称:Projects,代码行数:34,代码来源:ReadFile.cs

示例5: PerformPathping

 /// <summary>
 /// Performs a pathping
 /// </summary>
 /// <param name="ipaTarget">The target</param>
 /// <param name="iHopcount">The maximum hopcount</param>
 /// <param name="iTimeout">The timeout for each ping</param>
 /// <returns>An array of PingReplys for the whole path</returns>
 public static PingReply[] PerformPathping(IPAddress ipaTarget, int iHopcount, int iTimeout)
 {
     System.Collections.ArrayList arlPingReply = new System.Collections.ArrayList();
     Ping myPing = new Ping();
     PingReply prResult = null;
     int iTimeOutCnt = 0;
     for (int iC1 = 1; iC1 < iHopcount && iTimeOutCnt<5; iC1++)
     {
         prResult = myPing.Send(ipaTarget, iTimeout, new byte[10], new PingOptions(iC1, false));
         if (prResult.Status == IPStatus.Success)
         {
             iC1 = iHopcount;
             iTimeOutCnt = 0;
         }
         else if (prResult.Status == IPStatus.TtlExpired)
         {
             iTimeOutCnt = 0;
         }
         else if (prResult.Status == IPStatus.TimedOut)
         {
             iTimeOutCnt++;
         }
         arlPingReply.Add(prResult);
     }
     PingReply[] prReturnValue = new PingReply[arlPingReply.Count];
     for (int iC1 = 0; iC1 < arlPingReply.Count; iC1++)
     {
         prReturnValue[iC1] = (PingReply)arlPingReply[iC1];
     }
     return prReturnValue;
 }
开发者ID:Hagser,项目名称:csharp,代码行数:38,代码来源:Diag.cs

示例6: Ping

        /// <summary>
        /// Will use CheckOrResolveIpAddress() to get an IP Address, then try to ping it.
        /// </summary>
        /// <param name="toPing">The IP Address or Hostname to ping</param>
        /// <returns>Null if successful. The error message if an error occurred.</returns>
        private static string Ping(string toPing)
        {
            IPAddress ipAddress = CheckOrResolveIpAddress(toPing);

            if (ipAddress == null)
                return "Invalid IP Address/Hostname";

            Ping ping = new Ping();
            PingReply reply;

            try
            {
                reply = ping.Send(ipAddress);
            }
            catch (PingException pe)
            {
                return string.Format("Could not ping {0}, {1}", toPing, pe.Message);
            }
            catch (Exception e)
            {
                return string.Format("Could not ping {0}, {1}", toPing, e.Message);
            }

            if (reply != null && reply.Status == IPStatus.Success)
            {
                //string message = reply.Status.ToString();
                return null;
            }
            return string.Format("Could not ping {0}", toPing);
        }
开发者ID:aboyce,项目名称:Libraries,代码行数:35,代码来源:NetworkingHelper.cs

示例7: frm_wait_Shown

 private void frm_wait_Shown(object sender, EventArgs e)
 {
     frm_main frm = (frm_main)this.Owner;
     address = frm.current_pos;
     curr_pos = address;
     //Ping POS
     Ping png = new Ping();
     PingOptions opt = new PingOptions();
     opt.DontFragment = true;
     string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
     byte[] buffer = Encoding.ASCII.GetBytes (data);
     int timeout = 800;
     PingReply reply = png.Send(address, timeout, buffer, opt);
     if (reply.Status == IPStatus.Success)
     {
         if (Directory.Exists(@"\\" + address + @"\POS\Command\"))
         {
             address = @"\\" + address + @"\POS\Command\req18";
             using (File.Create(address)) { }
         }
         else
         {
             MessageBox.Show("Нету связи с POS терминалом или папка Command не доступна", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             this.Close();
         }
     }
     else
     {
         MessageBox.Show("Нету связи с POS терминалом или папка Command не доступна", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         this.Close();
     }
     bg_worker.WorkerSupportsCancellation = true;
     bg_worker.RunWorkerAsync();
 }
开发者ID:sylion,项目名称:SMarketSettings,代码行数:34,代码来源:frm_wait.cs

示例8: IsHostAccessible

        public static bool IsHostAccessible(string hostNameOrAddress)
        {
            if (String.IsNullOrEmpty(hostNameOrAddress))
                return false;
            using (var ping = new Ping())
            {
                PingReply reply;
                try
                {
                    reply = ping.Send(hostNameOrAddress, PingTimeout);
                }
                catch (Exception ex)
                {
                    if (ex is ArgumentNullException ||
                        ex is ArgumentOutOfRangeException ||
                        ex is InvalidOperationException ||
                        ex is SocketException )
                    {

                        return false;
                    }
                    throw;
                }
                if (reply != null) return reply.Status == IPStatus.Success;
            }
            return false;
        }
开发者ID:Ghawken,项目名称:FrontView,代码行数:27,代码来源:NetworkTools.cs

示例9: pingBaidu

        private void pingBaidu()
        {
            try
            {

                Ping p = new Ping();
                PingReply pr = p.Send("www.baidu.com");
                if (pr.Status == IPStatus.Success||true)
                {
                    MainWindow mw = new MainWindow();
                    mw.Show();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("本程序需要网络连接,请先配置好当前网络环境");
                    return;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("本程序需要网络连接,请先配置好当前网络环境");
                return;
            }
        }
开发者ID:dalinhuang,项目名称:presidentproject,代码行数:25,代码来源:Login.xaml.cs

示例10: Loop

        protected override void Loop(CancellationToken token)
        {
            _isConnected = false;

            while (token.IsCancellationRequested == false)
            {
                bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();
                if (isNetworkAvailable)
                {
                    NetworkInterface[] ifs = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (NetworkInterface @if in ifs)
                    {
                        // check for wireless and up
                        if (@if.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 && @if.OperationalStatus == OperationalStatus.Up)
                        {
                            var ping = new Ping();
                            PingReply result = ping.Send(_config.Hostname);
                            if (result != null && result.Status == IPStatus.Success)
                            {
                                _isConnected = true;
                                _connectionChanged(true);
                            }
                            else
                            {
                                // todo add timeout?
                                _isConnected = false;
                                _connectionChanged(false);
                            }
                        }
                    }
                }
                Thread.Sleep(1000);
            }
        }
开发者ID:AerynSun,项目名称:AR.Drone,代码行数:34,代码来源:NetworkWorker.cs

示例11: DoValidate

        public override bool DoValidate()
        {
            #if !NET_CORE
            Ping p = new Ping();//创建Ping对象p
            PingReply pr = p.Send("www.baidu.com", 30000);//向指定IP或者主机名的计算机发送ICMP协议的ping数据包

            if (pr != null && pr.Status == IPStatus.Success)//如果ping成功
            {
                return true;
            }

            #else
            HttpClient clinet = new HttpClient();
            IAsyncResult asyncResult = clinet.GetStringAsync("http://www.baidu.com");
            if (!asyncResult.AsyncWaitHandle.WaitOne(2000))
            {
                return false;
            }
            if (((Task<string>)asyncResult).Result.Contains("<title>百度一下,你就知道</title>"))
            {
                return true;
            }
            Thread.Sleep(100);
            #endif
            return false;
        }
开发者ID:GamesDesignArt,项目名称:DotnetSpider,代码行数:26,代码来源:DefalutNetworkValidater.cs

示例12: SendPing

        /// <summary>
        /// Ping network address
        /// </summary>
        /// <param name="address">IP Address or Hostname</param>
        /// <returns></returns>
        public static bool SendPing(string address, int tries)
        {
            int tries_count = 0;
            Ping pingSender = new Ping ();
            PingOptions options = new PingOptions ();

            // Use the default Ttl value which is 128,
            // but change the fragmentation behavior.
            options.DontFragment = true;

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes (data);
            int timeout = 120;
            while (tries_count < tries)
            {
                PingReply reply = pingSender.Send(address, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                    return true;

                tries_count++;
            }

            return false;
        }
开发者ID:Lootero4eg,项目名称:anvlib,代码行数:30,代码来源:PingSender.cs

示例13: PingAddress

        /* Ping an entered address */
        public void PingAddress(string addr)
        {
            List<IPStatus> replies = new List<IPStatus>();

            int count = 0;

            // send 4 pings
            while (count < 4)
            {
                // used to construct a 32 byte message
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 120;

                // intalize the ping object with ttl and no fragment options
                PingOptions PingSettings = new PingOptions(53, true);
                Ping Pinger = new Ping();

                // send the ping
                PingReply Reply = Pinger.Send(addr, timeout, buffer, PingSettings);

                replies.Add(Reply.Status);

                ++count;
            }

            // tracks the ammount of successful replies
            for (int i = 0; i < replies.Count; i++)
                if (replies[i] == IPStatus.Success)
                    scount++;
        }
开发者ID:Blankpanda,项目名称:chat_client,代码行数:32,代码来源:Net.cs

示例14: PingButton_Click

        async private void PingButton_Click(object sender, EventArgs e)
        {
            List<string> urls = new List<string>()
            {
                "www.habitat-spokane.org",
                "www.partnersintl.org",
                "www.iassist.org",
                "www.fh.org",
                "www.worldvision.org"
            };

            IPStatus status;

            Func<string, Task<IPStatus>> func =
                    async (localUrl) =>
                    {
                        Random random = new Random();
                        Ping ping = new Ping();
                        PingReply pingReply =
                            await ping.SendPingAsync(localUrl);
                        return pingReply.Status;
                    };

            StatusLabel.Text = "Pinging…";

            foreach(string url in urls)
            {
                status = await func(url);
                StatusLabel.Text +=
                    [email protected]"{ Environment.NewLine 
                    }{ url }: { status.ToString() } ({
                    Thread.CurrentThread.ManagedThreadId 
                    })";
            }
        }
开发者ID:troubleminds,项目名称:TIP,代码行数:35,代码来源:Listing18.23.AwaitsAndControlFlow.cs

示例15: PingIpOrDomainName

        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 objRPinReply = objPingSender.Send(strIpOrDname, intTimeout, buffer, objPinOptions);
                string strInfo = objRPinReply.Status.ToString();
                if (strInfo == "Success")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:305088020,项目名称:-SVN,代码行数:26,代码来源:Internet.cs


注:本文中的System.Net.NetworkInformation.Ping类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。