• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# NetworkInformation.Ping类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: TargetFound

        public string TargetFound(string target)
        {
            try
            {
                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;
                PingReply reply = pingSender.Send(target, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    return "targetfound";
                }
                else { return "targetnotfound"; }
            }
            catch(Exception e)
            {
                string CaughtException = e.ToString();
                return CaughtException.Substring(0, CaughtException.IndexOf(Environment.NewLine));
            }
        }
开发者ID:jeremysiebers,项目名称:Siebwalde-Source,代码行数:28,代码来源:PingTarget.cs


示例17: Trace

 public static void Trace(IPAddress destination, Func<IPAddress, TracertNode, bool> callback)
 {
     if (destination == null)
     {
         throw new ArgumentNullException("destination");
     }
     else
     {
         if (callback == null)
         {
             throw new ArgumentNullException("callback");
         }
         else
         {
             var syncroot = new object();
             var buffer = new byte[INT_BufferSize];
             var options = new PingOptions(1, true);
             var ping = new Ping();
             ping.PingCompleted += (sender, e) =>
             {
                 var address = e.Reply.Address;
                 var status = e.Reply.Status;
                 back:
                 var done = !callback.Invoke(destination, new TracertNode(address, status, e.Reply.Options.Ttl)) || address.Equals(destination);
                 if (done)
                 {
                     try
                     {
                         if (ping != null)
                         {
                             ping.Dispose();
                         }
                     }
                     finally
                     {
                         ping = null;
                     }
                 }
                 else
                 {
                     lock (syncroot)
                     {
                         if (ping == null)
                         {
                             address = destination;
                             status = IPStatus.Unknown;
                             goto back;
                         }
                         else
                         {
                             options.Ttl++;
                             ping.SendAsync(destination, INT_TimeoutMilliseconds, buffer, options, null);
                         }
                     }
                 }
             };
             ping.SendAsync(destination, INT_TimeoutMilliseconds, buffer, options, null);
         }
     }
 }
开发者ID:mesheets,项目名称:Theraot-CF,代码行数:60,代码来源:TraceRoute.cs


示例18: CanPing

        public bool CanPing(string address)
        {
            Ping ping = new Ping();

            try
            {
                PingReply reply = ping.Send(address);
                if (reply == null) return false;

                if (reply.Status == IPStatus.Success)
                {
                    this.Log.Debug("On-Line!");
                    return true;
                }
                else
                {
                    this.Log.Debug("Off-Line");
                    return false;
                }
            }
            catch (PingException)
            {
                this.Log.Debug("Off-Line");
                return false;
            }
        }
开发者ID:VeronicaMartin,项目名称:Open-Source-Automation,代码行数:26,代码来源:NetworkMonitor.cs


示例19: Ping

        public static PingStatus Ping(string deviceName, PingerOptions options)
        {
            Ping pinger = new Ping();
            PingOptions pingOptions = new PingOptions() { DontFragment = options.DontFragment };
            
            // Create a buffer of 32 bytes of data to be transmitted.

            byte a = Encoding.ASCII.GetBytes("a")[0];
            byte[] buffer = new byte[options.PayloadSize]; // Encoding.ASCII.GetBytes(data);
            for (int i = 0; i < options.PayloadSize; i++)
            {
                buffer[i] = a;
            }

            try
            {
                PingReply reply = pinger.Send(deviceName, options.Timeout, buffer, pingOptions);
                if (reply.Status == IPStatus.Success)
                {
                    //Ping was successful
                    return new PingStatus(true, (int)reply.Status, reply.RoundtripTime);
                }
                //Ping failed
                return new PingStatus(false, (int)reply.Status, reply.RoundtripTime);
            }
            catch (Exception)
            {
                return new PingStatus(false, 99999, 99999);
            }
        }
开发者ID:nhunyady,项目名称:SharpNET.Utilities,代码行数:30,代码来源:Pinger.cs


示例20: RemoteEnvironment

        public RemoteEnvironment(string ipAddress, string userName, string password, string psExecPath)
        {
            IpAddress = ipAddress;
              UserName = userName;
              Password = password;
            _psExecPath = psExecPath;

            // wait for ping
              RetryUtility.RetryAction(() =>
            {
              var ping = new Ping();
              var reply = ping.Send(IpAddress);
              OsTestLogger.WriteLine(string.Format("Pinging ip:{0}, reply: {1}", ipAddress, reply.Status));
              if (reply.Status != IPStatus.Success)
            throw new InvalidOperationException(string.Format("Remote IP {0} ping returns {1}", ipAddress, reply.Status));
            }, 50, 5000);

              // give time for the RPC service to start
              RetryUtility.RetryAction(() => { WmiWrapperInstance = new WmiWrapper(ipAddress, userName, password); }, 10, 5000);
              WindowsShellInstance = new WindowsShell(this, psExecPath);
              //this will populate the GuestEnvironmentVariables. Short time after start APPDATA may be empty
              RetryUtility.RetryAction( InvalidateCachedGuestEnvironmentVariables, 10, 10000);

              IsUACEnabled = CheckIsUAC();
        }
开发者ID:van800,项目名称:OsTestFramework,代码行数:25,代码来源:RemoteEnvironment.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# NetworkInformation.PingOptions类代码示例发布时间:2022-05-26
下一篇:
C# NetworkInformation.PhysicalAddress类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap