Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
コード例 #1
0
ファイル: TraceRoute.cs プロジェクト: mesheets/Theraot-CF
 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);
         }
     }
 }
コード例 #2
0
ファイル: Pinger.cs プロジェクト: woeishi/VVVV.ARDrone
		private void DoPings()
		{
			while (work)
			{
				Thread.Sleep(250);
				while (checkPing)
				{
					try
					{
						Ping ping = new Ping();
						PingReply reply = ping.Send(host.IPAddress);
						
						if (reply.Status == IPStatus.Success)
						{
							checkPing = false;
							if ((int)host.Status <= (int)DroneStatus.NotConnected)
									host.Status = DroneStatus.Available;
						}
						ping.Dispose();
					}
					catch
					{
						/* ignore not pingable
						if ((int)host.Status == (int)DroneStatus.NotConnected)
							host.Status = DroneStatus.Invalid; */
					}
					Thread.Sleep(250);
				}
			}
		}
コード例 #3
0
ファイル: NetworkPing.cs プロジェクト: 5dollartools/NAM
 public static bool Available(string IPorHostname)
 {
     bool bAvailable = false;
     Ping ping = new Ping();
     try
     {
         PingReply pingReply = ping.Send(IPorHostname, timeout);
         if (pingReply.Status == IPStatus.Success)
         {
             bAvailable = true;
         }
     }
     catch (Exception)
     {
         bAvailable = false;
     }
     finally
     {
         if ( ping!=null)
         {
             ping.Dispose();
             ping = null;
         }
     }
     return bAvailable;
 }
コード例 #4
0
 private bool ping_ip()
 {
     try
     {
         Ping      ping      = new System.Net.NetworkInformation.Ping();
         PingReply pingReply = null;
         pingReply = ping.Send((string)ping_resource);
         ping.Dispose();
         return(pingReply.Status == IPStatus.Success);
     }
     catch
     {
         return(false);
     }
 }
コード例 #5
0
ファイル: Updater.cs プロジェクト: pleonex/MiConsulta
        public static bool Check_Internet()
        {
            Ping ping = new Ping();
            PingReply reply;
            try { reply = ping.Send(ping_web, 1000); }
            catch (Exception e) { Console.WriteLine("Exception at ping\n {0}", e.Message); return false; }
            ping.Dispose();
            ping = null;

            Console.WriteLine("Ping to google.es -> {0}", Enum.GetName(typeof(IPStatus), reply.Status));
            if (reply.Status != IPStatus.Success)
                return false;
            else
                return true;
        }
コード例 #6
0
    public static bool Ping(string hostNameOrAddress, int timeout, out Exception error)
    {
        var success = false;

        error = null;
        var sw = new System.Diagnostics.Stopwatch();

        sw.Start();
        System.Net.NetworkInformation.PingReply reply = null;
        Exception replyError = null;
        // Use proper threading, because other asynchronous classes
        // like "Tasks" have problems with Ping.
        var ts = new System.Threading.ThreadStart(delegate()
        {
            var ping = new System.Net.NetworkInformation.Ping();
            try
            {
                reply = ping.Send(hostNameOrAddress);
            }
            catch (Exception ex)
            {
                replyError = ex;
            }
            ping.Dispose();
        });
        var t = new System.Threading.Thread(ts);

        t.Start();
        t.Join(timeout);
        if (reply != null)
        {
            success = (reply.Status == System.Net.NetworkInformation.IPStatus.Success);
        }
        else if (replyError != null)
        {
            error = replyError;
        }
        else
        {
            error = new Exception("Ping timed out (" + timeout.ToString() + "): " + sw.Elapsed.ToString());
        }
        return(success);
    }
コード例 #7
0
        static void Main(string[] args)
        {
            String intermediateHost;
            Ping pinger = new Ping();
            String data = "0123456789ABCDEF";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            PingOptions options = new PingOptions();

            IPHostEntry target = Dns.GetHostEntry(args[0]);
            bool isDestination = false;
            for (int i = 1; i <= 30; i++)
            {
                options.Ttl = i;
                PingReply reply = pinger.Send(target.AddressList[0], 30, buffer, options);
                switch (reply.Status)
                {
                    case IPStatus.TimedOut:
                    case IPStatus.TtlExpired:
                    case IPStatus.Success:
                        Console.Write("<{0}ms\t", reply.RoundtripTime);

                        if (reply.Address.Equals(target.AddressList[0]))
                        {
                            isDestination = true;
                        }
                        intermediateHost = reply.Address.ToString();
                        break;
                    default:
                        Console.WriteLine("*\t");
                        break;
                }
            }

            Console.WriteLine("\t{0}",intermediateHost);
            if (isDestination)
            {
                break;
            }

            pinger.Dispose();
        }
コード例 #8
0
        public static bool PingHost(string nameOrAddress)
        {
            bool pingable = false;

            System.Net.NetworkInformation.Ping pinger = null;

            try
            {
                pinger = new System.Net.NetworkInformation.Ping();
                PingReply reply = pinger.Send(nameOrAddress);
                pingable = reply.Status == IPStatus.Success;
            }
            catch (PingException) { }
            finally
            {
                if (pinger != null)
                {
                    pinger.Dispose();
                }
            }
            return(pingable);
        }
コード例 #9
0
        /// <summary>
        /// 单独ping一个ip
        /// </summary>
        private void PingStandalone()
        {
            label8.Text = "正在Ping";
            var    ipText = textBox1.Text;
            Thread thread = new Thread(() =>
            {
                System.Net.NetworkInformation.Ping ping = null;
                try
                {
                    ping = new System.Net.NetworkInformation.Ping();
                    PingReply pingReply = ping.Send(ipText, int.Parse(textBox7.Text));
                    var pingable        = pingReply?.Status == IPStatus.Success;
                    if (pingable)
                    {
                        label8.Text      = "通过";
                        label8.ForeColor = Color.Green;
                    }
                    else
                    {
                        label8.Text      = "不通";
                        label8.ForeColor = Color.Red;
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    Console.WriteLine(ipText);
                    label8.Text = "";
                    MessageBox.Show($"{exception.Message}{exception.GetBaseException().Message}", "错误");
                }
                finally
                {
                    ping?.Dispose();
                }
            });

            thread.Start();
        }
コード例 #10
0
ファイル: LED.cs プロジェクト: puyd/AndonSys.Test
            /// <summary>
            /// ping大屏地址
            /// </summary>
            /// <param name="timeout">超时毫秒数</param>
            /// <returns>ping通返回true,否则返回false</returns>
            public bool Ping(int timeout)
            {
                if (IP == "0.0.0.0") return false; 
                
                Ping p = new Ping();

                PingReply r = p.Send(IP,timeout);

                p.Dispose();

                IsConnected = (r.Status == IPStatus.Success);

                return (r.Status == IPStatus.Success);
            }
コード例 #11
0
        internal static bool Ping(string hostname)
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();


            // Create a buffer of 32 bytes of data to be transmitted.
            const string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);

            //TODO: Move the Ping timeout to the settings file 
            const int timeout = 10000;

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


            if (reply.Status == IPStatus.Success)
            {
                pingSender.Dispose();
                return true;
            }
            reply = pingSender.Send(hostname, timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                pingSender.Dispose();
                return true;
            }
            pingSender.Dispose();
            return false;
        }
コード例 #12
0
ファイル: TraceRoute.cs プロジェクト: RSchwoerer/Terminals
        private void ProcessHop(IPAddress address, IPStatus status, string time)
        {
            Int64 roundTripTime = 0;

            if (status == IPStatus.Success || status == IPStatus.TtlExpired)
            {
                System.Net.NetworkInformation.Ping ping2 = new System.Net.NetworkInformation.Ping();

                try
                {
                    // Do another ping to get the roundtrip time per address.
                    PingReply reply = ping2.Send(address, this.HopTimeOut);
                    roundTripTime = reply.RoundtripTime;
                    status = reply.Status;
                }
                catch (Exception ex)
                {
                    Log.Info(String.Empty, ex);
                }
                finally
                {
                    ping2.Dispose();
                    ping2 = null;
                }
            }

            if (this.cancel)
                return;

            TraceRouteHopData hop = new TraceRouteHopData(this.counter++, address, roundTripTime, status, time);
            try
            {
                if (status == IPStatus.Success && this.ResolveNames)
                {
                    IPHostEntry entry = Dns.GetHostEntry(address);
                    hop.HostName = entry.HostName;
                }
            }
            catch (SocketException)
            {
                // No such host is known error.
                hop.HostName = String.Empty;
            }

            lock (this.hopList)
                this.hopList.Add(hop);

            if (this.RouteHopFound != null)
                this.RouteHopFound(this, new RouteHopFoundEventArgs(hop, this.Idle));

            this.Idle = address.Equals(this.destinationIP);

            lock (this.hopList)
            {
                if (!this.Idle && this.hopList.Count >= this.HopLimit - 1)
                    this.ProcessHop(this.destinationIP, IPStatus.Success, DateTime.Now.ToLongTimeString());
            }

            if (this.Idle)
            {
                this.OnCompleted();
                this.Dispose();
            }
        }
コード例 #13
0
ファイル: Tracert.cs プロジェクト: sinaaslani/kids.bmi.ir
        protected void ProcessNode(IPAddress address, IPStatus status)
        {
            long roundTripTime = 0;

            if (status == IPStatus.TtlExpired || status == IPStatus.Success)
            {
                var pingIntermediate = new Ping();

                try
                {
                    //Compute roundtrip time to the address by pinging it
                    PingReply reply = pingIntermediate.Send(address, _timeout);
                    roundTripTime = reply.RoundtripTime;
                    status = reply.Status;
                }
                catch (PingException e)
                {
                    //Do nothing
                    System.Diagnostics.Trace.WriteLine(e);
                }
                finally
                {
                    pingIntermediate.Dispose();
                }
            }

            var node = new TracertNode(address, roundTripTime, status);

            lock (_nodes)
            {
                _nodes.Add(node);
            }

            if (RouteNodeFound != null)
                RouteNodeFound(this, new RouteNodeFoundEventArgs(node, IsDone));

            IsDone = address.Equals(_destination);

            lock (_nodes)
            {
                if (!IsDone && _nodes.Count >= _maxHops - 1)
                    ProcessNode(_destination, IPStatus.Success);
            }
        }
コード例 #14
0
ファイル: AddServer.cs プロジェクト: fronn/win-net-mon
 private IPStatus PingIp(String ip)
 {
     Ping p = new Ping();
     if (!String.IsNullOrEmpty(ip))
     {
         try
         {
             PingReply pr = p.Send(ip);
             p.Dispose();
             if (pr != null)
                 return pr.Status;
         }
         catch (Exception ex)
         {
             p.Dispose();
             ToLog = "Error: " + ex.Message;
         }
     }
     else
         p.Dispose();
     return IPStatus.Unknown;
 }
コード例 #15
0
ファイル: Control.cs プロジェクト: Simsso/Crusades
        void PingTimer_Tick(object sender, EventArgs e)
        {
            (new Thread(() =>
            {
                Thread.CurrentThread.Priority = ThreadPriority.Lowest;
                Thread.CurrentThread.IsBackground = true; // cancel this thread when the window is being closed

                Ping Ping = new Ping();
                try
                {
                    long PingTime = Ping.Send(Server.ServerHost).RoundtripTime;

                    MainWindow.Dispatcher.BeginInvoke(
                    (Action)(() =>
                    {
                        MainWindow.Label_PingInfo.Content = R.String("Ping") + ": " + PingTime.ToString() + " ms";
                    }));
                }
                catch (Exception)
                {
                    MainWindow.Dispatcher.BeginInvoke(
                    (Action)(() =>
                    {
                        MainWindow.Label_PingInfo.Content = R.String("NoNetworkConnection");
                    }));
                }
                finally
                {
                    Ping.Dispose();
                }
            })).Start();
        }
コード例 #16
0
ファイル: Ping.cs プロジェクト: NullProjects/METAbolt
        public void StartPing(object argument)
        {
            if (IsOffline())
                return;

            IPAddress ip = (IPAddress)argument;

            //set options ttl=128 and no fragmentation
            PingOptions options = new PingOptions(128, true);

            //create a Ping object
            Ping ping = new Ping();

            //32 empty bytes buffer
            byte[] data = new byte[32];

            int received = 0;
            List<long> responseTimes = new List<long>();

            string resp = string.Empty;

            //ping 4 times
            for (int i = 0; i < 4; i++)
            {
                PingReply reply = ping.Send(ip, 1000, data, options);

                if (reply != null)
                {
                    switch (reply.Status)
                    {
                        case IPStatus.Success:
                            resp = "Reply from " + reply.Address + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms TTL=" + reply.Options.Ttl;
                            PingEventArgs pe = new PingEventArgs(resp);
                            Change(this, pe);
                            received++;
                            responseTimes.Add(reply.RoundtripTime);
                            break;
                        case IPStatus.TimedOut:
                            pe = new PingEventArgs("Request timed out.");
                            Change(this, pe);
                            break;
                        default:
                            pe = new PingEventArgs("Ping failed " + reply.Status.ToString());
                            Change(this, pe);
                            break;
                    }
                }
                else
                {
                    PingEventArgs pe = new PingEventArgs("Ping failed for an unknown reason");
                    Change(this, pe);
                }

                reply = null;
            }

            ping.Dispose();

            //statistics calculations
            long averageTime = -1;
            long minimumTime = 0;
            long maximumTime = 0;

            for (int i = 0; i < responseTimes.Count; i++)
            {
                if (i == 0)
                {
                    minimumTime = responseTimes[i];
                    maximumTime = responseTimes[i];
                }
                else
                {
                    if (responseTimes[i] > maximumTime)
                    {
                        maximumTime = responseTimes[i];
                    }
                    if (responseTimes[i] < minimumTime)
                    {
                        minimumTime = responseTimes[i];
                    }
                }
                averageTime += responseTimes[i];
            }

            StringBuilder statistics = new StringBuilder();
            statistics.AppendLine();
            statistics.AppendLine();
            statistics.AppendFormat("Ping statistics for {0}:", ip.ToString());
            statistics.AppendLine();
            statistics.AppendFormat("   Packets: Sent = 4, " +
                "Received = {0}, Lost = {1} <{2}% loss>,",
                received, 4 - received, Convert.ToInt32(((4 - received) * 100) / 4));
            statistics.AppendLine();
            statistics.AppendLine();

            //show only if loss is not 100%
            if (averageTime != -1)
            {
                statistics.Append("Approximate round trip times in milli-seconds:");
                statistics.AppendLine();
                statistics.AppendFormat("    Minimum = {0}ms, " +
                    "Maximum = {1}ms, Average = {2}ms",
                    minimumTime, maximumTime, (long)(averageTime / received));
            }

            PingEventArgs pes = new PingEventArgs(statistics.ToString());
            Change(this, pes);
        }
コード例 #17
0
ファイル: MainWindow.xaml.cs プロジェクト: LongQin/DAMS
 /// <summary>
 /// ping 具体的网址看能否ping通
 /// </summary>
 /// <param name="strNetAdd"></param>
 /// <returns></returns>
 private static bool PingNetAddress(string strNetAdd)
 {
     bool Flage = false;
     Ping ping = new Ping();
     try
     {
         PingReply pr = ping.Send(strNetAdd, 3000);
         if (pr.Status == IPStatus.TimedOut)
         {
             Flage = false;
         }
         if (pr.Status == IPStatus.Success)
         {
             Flage = true;
         }
         else
         {
             Flage = false;
         }
     }
     catch
     {
         Flage = false;
     }
     finally
     {
         ping.Dispose();
     }
     return Flage;
 }
コード例 #18
0
ファイル: Main.cs プロジェクト: dknoodle/ConnectionMonitor
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            bool firstrun = true;

            DateTime downtimestart = DateTime.Now;
            DateTime downtimeend = DateTime.Now;

            ConnectionStatus laststatus = ConnectionStatus.Unknown;

            int count = 0;
            long total = 0;

            // Only keep the last 50 pings in the avg
            if (count >= 50)
            {
                total = total / count;
                count = 1;
            }

            while (!worker.CancellationPending)
            {
                StringBuilder history = new StringBuilder();
                StringBuilder log = new StringBuilder();
                ProgressData pd = new ProgressData() { History = string.Empty, Log = string.Empty };

                Ping pingSender = new Ping();

                try
                {
                    IPAddress address = IPAddress.Parse(Properties.Settings.Default.DefaultGatewayIP);
                    PingReply reply = pingSender.Send(address, 5000);

                    count++;
                    total = total + reply.RoundtripTime;

                    if (reply.Status == IPStatus.Success)
                    {
                        if (firstrun)
                        {
                            history.AppendLine("Connection Status: Up");
                            log.AppendLine("Connection Status: Up");
                            firstrun = false;
                        }

                        if (laststatus == ConnectionStatus.Down)
                        {
                            downtimeend = DateTime.Now;
                            var span = downtimeend - downtimestart;

                            string status = string.Format("Connection Up: {0}    Downtime: {1} hours - {2} minutes - {3} seconds", DateTime.Now, span.Hours, span.Minutes, span.Seconds);
                            log.AppendLine(status);
                            history.AppendLine(status);
                        }

                        laststatus = ConnectionStatus.Up;

                        if (verbose) { history.AppendLine(string.Format("Time: {0}     Address: {1}     Status: {2}     RoundTrip: {3} ms     Average: {4} ms", DateTime.Now, address.ToString(), reply.Status, reply.RoundtripTime, total / count)); }
                    }
                    else
                    {
                        firstrun = false;
                        count = 0;
                        total = 0;

                        if (laststatus != ConnectionStatus.Down)
                        {
                            downtimestart = DateTime.Now;

                            string status = string.Format("Connection Down: {0}", DateTime.Now);
                            log.AppendLine(status);
                            history.AppendLine(status);
                        }

                        laststatus = ConnectionStatus.Down;

                        if (verbose) { history.AppendLine(string.Format("Time: {0}     Address: {1}     Status: {2}     RoundTrip: {3} ms", DateTime.Now, address.ToString(), reply.Status, reply.RoundtripTime)); }
                    }
                }
                catch (PingException pe)
                {
                    history.AppendLine(pe.Message);
                }
                catch (NetworkInformationException net)
                {
                    history.AppendLine(net.Message);
                }
                catch (Exception ex)
                {
                    history.AppendLine(ex.Message);
                }
                finally
                {
                    pingSender.Dispose();
                }

                if (history.Length > 0) { pd.History = history.ToString(); }
                if (log.Length > 0) { pd.Log = log.ToString(); }

                worker.ReportProgress(0, pd);

                history = null;
                log = null;

                System.Threading.Thread.Sleep(3000);
            }
        }
コード例 #19
0
ファイル: LED.cs プロジェクト: puyd/AndonSys.Test
            /// <summary>
            /// ping大屏地址
            /// </summary>
            /// <param name="timeout">超时毫秒数</param>
            /// <returns>ping通返回true,否则返回false</returns>
            public bool Ping(int timeout)
            {
                if (IP == "0.0.0.0") return false;

                long s = DateTime.Now.Ticks;

                Ping ping = new Ping(); 
                
                PingReply r = ping.Send(IP, timeout);

                ping.Dispose();

                IsConnected = (r.Status == IPStatus.Success);

                TimeSpan t = new TimeSpan(DateTime.Now.Ticks - s);

                //Debug.WriteLine(t.TotalSeconds);

                return (r.Status == IPStatus.Success);
            }
コード例 #20
0
ファイル: WMIProvider.cs プロジェクト: przemo098/ccmmanager
        private bool PingHost()
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            string data = "";
            byte[] buffer = Encoding.ASCII.GetBytes(data);

            int timeout = 400;
            try
            {
                PingReply reply = pingSender.Send(this.Hostname, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    pingSender.Dispose();
                    return true;
                }
                else
                {
                    pingSender.Dispose();
                    return false;
                }
            }
            catch
            {
                pingSender.Dispose();
                return false;
            }
        }
コード例 #21
0
        public Result Run(int iterations)
        {
            try
            {
                long totalElasped = 0;

                for (int i = 0; i < iterations; i++)
                {
                    Ping pingSender = new Ping();
                    PingReply reply = pingSender.Send(Hostname);

                    if (reply.Status == IPStatus.Success)
                    {
                        totalElasped += reply.RoundtripTime;
                    }

                    pingSender.Dispose();
                }

                return new Result(Name, (totalElasped / iterations).ToString());
            }
            catch
            {
                return new Result(Name, "-1");
            }
        }
        private static bool PerformPingCheckReply
            (string hostname, byte[] buffer,
            PingOptions options, Ping pingSender,
            int timeout)
        {


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


            if (reply != null
                && reply.Status
                == IPStatus.Success)
            {
                pingSender.Dispose();
                return true;
            }


            return false;
        }
コード例 #23
0
        private void ProcessHop(IPAddress address, IPStatus status, string time)
        {
            Int64 roundTripTime = 0;

            if (status == IPStatus.Success || status == IPStatus.TtlExpired)
            {
                System.Net.NetworkInformation.Ping ping2 = new System.Net.NetworkInformation.Ping();

                try
                {
                    // Do another ping to get the roundtrip time per address.
                    PingReply reply = ping2.Send(address, this.HopTimeOut);
                    roundTripTime = reply.RoundtripTime;
                    status        = reply.Status;
                }
                catch (Exception ex)
                {
                    Log.Info(String.Empty, ex);
                }
                finally
                {
                    ping2.Dispose();
                    ping2 = null;
                }
            }

            if (this.cancel)
            {
                return;
            }

            TraceRouteHopData hop = new TraceRouteHopData(this.counter++, address, roundTripTime, status, time);

            try
            {
                if (status == IPStatus.Success && this.ResolveNames)
                {
                    IPHostEntry entry = Dns.GetHostEntry(address);
                    hop.HostName = entry.HostName;
                }
            }
            catch (SocketException)
            {
                // No such host is known error.
                hop.HostName = String.Empty;
            }

            lock (this.hopList)
                this.hopList.Add(hop);

            if (this.RouteHopFound != null)
            {
                this.RouteHopFound(this, new RouteHopFoundEventArgs(hop, this.Idle));
            }

            this.Idle = address.Equals(this.destinationIP);

            lock (this.hopList)
            {
                if (!this.Idle && this.hopList.Count >= this.HopLimit - 1)
                {
                    this.ProcessHop(this.destinationIP, IPStatus.Success, DateTime.Now.ToLongTimeString());
                }
            }

            if (this.Idle)
            {
                this.OnCompleted();
                this.Dispose();
            }
        }
コード例 #24
0
 private Boolean IsConnectedToInternet()
 {
     Boolean result = false;
     Ping ping = new Ping();
     try
     {
         PingReply reply = ping.Send(host, 1000); //expect a response within 1 second
         if (reply.Status == IPStatus.Success)
             return true;
     }
     catch { }
     finally
     {
         ping.Dispose();
     }
     return result;
 }
コード例 #25
0
ファイル: NetworkMonitor.cs プロジェクト: fronn/win-net-mon
 private void ManualPingServer(object ipAddress)
 {
     String ip = ipAddress.ToString();
     Invoke(new UpdateStatusBarDelegate(UpdateStatusBar), "Pinging " + ip);
     //Invoke(new UpdateLogDelegate(UpdateLog), "Pinging " + ip);
     Ping p = new Ping();
     try
     {
         PingReply pr = p.Send(ip);
         if (pr != null && pr.Status == IPStatus.Success)
         {
             IPHostEntry hostEntry = Dns.GetHostEntry(ip);
             if (hostEntry.HostName != "")
                 Invoke(new UpdateServerBrowserDelegate(UpdateServerBrowser), new[] { ip, hostEntry.HostName });
             else
                 Invoke(new UpdateServerBrowserDelegate(UpdateServerBrowser), new[] { ip, ip });
         }
         //Invoke(new UpdateStatusBarDelegate(UpdateStatusBar), "Finished pinging: " + ip);
     }
     catch (Exception)
     {
         Invoke(new UpdateLogDelegate(UpdateLog), "Unable to access IP: " + ip);
         //Invoke(new UpdateStatusBarDelegate(UpdateStatusBar), "Unsuccessful ping of: " + ip);
         Logger.Instance.Log(this.GetType(), LogType.Info, "Unable to access IP: " + ip);
     }
     finally
     {
         p.Dispose();
     }
 }
        internal static bool Ping(string hostname)
        {


            var pingSender
                = new Ping();

            var options
                = new PingOptions();


            var buffer = CreateTransmitBuffer();


            //TODO: Move the Ping timeout to the settings file 
            const int timeout = 10000;


            if (PerformPingCheckReply
                (hostname, buffer,
                options, pingSender,
                timeout))
                return true;


            if (PerformPingCheckReply
                (hostname, buffer,
                options, pingSender,
                timeout))
                return true;



            pingSender.Dispose();            
            return false;

        }
コード例 #27
0
        public bool PingComputer(byte[] bIP)
        {
            bool result = false;
            Ping p = null;
            try
            {
                string s = "http://" + StaticFunc.GetComputerFromIP(bIP);

                Uri url = new Uri(s);
                string pingurl = string.Format("{0}", url.Host);
                string host = pingurl;

                p = new Ping();
                PingReply reply = p.Send(host, PingTimeout);
                if (reply.Status == IPStatus.Success)
                {
                    p.Dispose();
                    return true;
                }
                p.Dispose();
            }
            catch (Exception Ex)
            {
                if (p != null)
                    p.Dispose();
               MessageBox.Show(Ex.Message, "ERROR");
            }
            return result;
        }
コード例 #28
0
        /// <summary>
        /// 创建多个线程ping指定范围的ip
        /// </summary>
        private void StartPing()
        {
            if (int.Parse(textBox2.Text) > 255 || int.Parse(textBox2.Text) < 0 ||
                int.Parse(textBox3.Text) > 255 || int.Parse(textBox3.Text) < 0 ||
                int.Parse(textBox4.Text) > 255 || int.Parse(textBox4.Text) < 0 ||
                int.Parse(textBox5.Text) > 255 || int.Parse(textBox5.Text) < 0 ||
                int.Parse(textBox6.Text) > 255 || int.Parse(textBox6.Text) < 0)
            {
                MessageBox.Show("IP输入不正确!", "错误");
                return;
            }

            SaveConfig();

            for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
            {
                var label = tableLayoutPanel1.Controls[i];
                label.BackColor = Color.FromArgb(0, 240, 240, 240);
            }

            for (int i = int.Parse(textBox5.Text) - 1; i <= int.Parse(textBox6.Text) - 1; i++)
            {
                var tableLabel = SearchLabelFromTableLayoutPanel((i + 1).ToString());
                tableLabel.BackColor = DefaultBackColor;

                var thread = new Thread(() =>
                {
                    System.Net.NetworkInformation.Ping ping = null;
                    var ipAddress = $"{textBox2.Text}.{textBox3.Text}.{textBox4.Text}.{tableLabel.Text}";
                    try
                    {
                        ping = new System.Net.NetworkInformation.Ping();

                        PingReply pingReply = ping.Send(ipAddress, int.Parse(textBox7.Text));
                        var pingable        = pingReply.Status == IPStatus.Success;
                        if (pingable)
                        {
                            tableLabel.BackColor = Color.Green;
                        }
                        else
                        {
                            tableLabel.BackColor = Color.Red;
                        }
                    }
                    catch (Exception exception)
                    {
                        ping = new System.Net.NetworkInformation.Ping();

                        PingReply pingReply  = ping.Send(ipAddress);
                        var pingable         = pingReply?.Status == IPStatus.Success;
                        tableLabel.BackColor = pingable ? Color.Green : Color.Red;

                        Console.WriteLine(ipAddress);
                        Console.WriteLine(exception);
                    }
                    finally
                    {
                        ping?.Dispose();
                    }
                });
                try
                {
                    thread.Start();
                }
                catch (Exception exception)
                {
                    thread.Start();
                }
            }
        }