public static bool PingHost(string nameOrAddress) { var canPing = false; Ping ping = null; try { ping = new Ping(); var reply = ping.Send(nameOrAddress); if (reply != null) { canPing = reply.Status == IPStatus.Success; } } catch (PingException) { // Discard PingExceptions and return false; } finally { ping?.Dispose(); } return(canPing); }
public static bool IsOnline(string target) { if (string.IsNullOrEmpty(target)) { return(false); } if (target is "127.0.0.1" or "localhost") { return(true); } var pingable = false; Ping?ping = null; try { ping = new Ping(); var reply = ping.Send(target); pingable = reply.Status == IPStatus.Success; } catch (PingException) { //ignore } finally { ping?.Dispose(); } return(pingable); }
public bool IsPingable(string ipAddress) { if (ipAddress == null) { return(false); } var isPingable = false; Ping pinger = null; try { pinger = new Ping(); var reply = pinger.Send(ipAddress, 500); if (reply != null) { isPingable = reply.Status == IPStatus.Success; } } catch (PingException) { return(false); } finally { pinger?.Dispose(); } return(isPingable); }
private void TestServer(string server) { Ping pinger = null; var delay = -1; Task.Run(() => { try { pinger = new Ping(); var reply = pinger.Send(server); var pingRelied = reply.Status == IPStatus.Success; if (pingRelied) { delay = (int)reply.RoundtripTime; } else { delay = -1; } } catch (PingException) { // Discard PingExceptions and return false; } finally { pinger?.Dispose(); } sync.Send(ShowDelay, delay); }); }
public static bool PingHost(string nameOrAddress) { bool pingable = false; Ping pinger = null; try { pinger = new Ping(); PingReply reply = pinger.Send(nameOrAddress, 500); if (reply != null) { pingable = reply.Status == IPStatus.Success; } } catch (PingException) { // Discard PingExceptions and return false; } finally { pinger?.Dispose(); } return(pingable); }
private PingReply SendCancellablePing( IPAddress targetAddress, int timeout, byte[] buffer, PingOptions pingOptions, Stopwatch?timer = null) { try { _sender = new Ping(); timer?.Start(); // 'SendPingAsync' always uses the default synchronization context (threadpool). // This is what we want to avoid the deadlock resulted by async work being scheduled back to the // pipeline thread due to a change of the current synchronization context of the pipeline thread. return(_sender.SendPingAsync(targetAddress, timeout, buffer, pingOptions).GetAwaiter().GetResult()); } catch (PingException ex) when(ex.InnerException is TaskCanceledException) { // The only cancellation we have implemented is on pipeline stops via StopProcessing(). throw new PipelineStoppedException(); } finally { timer?.Stop(); _sender?.Dispose(); _sender = null; } }
protected override void Dispose(bool disposing) { try { if (!IsDisposed && disposing) { if (_stateMachine != null) { _subscribeStateMachineAllEvents(false); } if (_timer != null) { _subscribeTimerAllEvents(false); _isStart = false; _timer.Stop(); _timer.Dispose(); } _ping?.Dispose(); } } finally { base.Dispose(disposing); } }
public static bool PingHost(string hostName, ILogger logger, int timeout) { var pingable = false; Ping pinger = null; //const int timeout = 10000; try { pinger = new Ping(); var reply = pinger.Send(hostName, timeout); if (reply != null) { pingable = reply.Status == IPStatus.Success; } } catch (Exception ex) { // Discard PingExceptions and return false; logger.LogError($"Error pinging remote host {hostName}, cant write in shared folder: " + ex.Message); pingable = false; } finally { pinger?.Dispose(); } return(pingable); }
private static int TestServer(string server) { // 测试延迟 Ping pinger = null; var delay = -1; try { pinger = new Ping(); var reply = pinger.Send(server); var pingRelied = reply.Status == IPStatus.Success; if (pingRelied) { delay = (int)reply.RoundtripTime; } else { delay = -1; } } catch (PingException) { // Discard PingExceptions and return false; } finally { pinger?.Dispose(); } return(delay); }
public void Close() { if (ping != null) { ping.Dispose(); ping = null; } pingThread.Abort(); }
protected override void Dispose(bool manual) { if (!manual) { return; } Ping.Dispose(); Pong.Dispose(); }
public static void Trace(IPAddress destination, Func <IPAddress, TracertNode, bool> callback) { const int BufferSize = 32; const int TimeoutMilliseconds = 1000; if (destination == null) { throw new ArgumentNullException("destination"); } if (callback == null) { throw new ArgumentNullException("callback"); } var syncroot = new object(); var buffer = new byte[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; } options.Ttl++; ping.SendAsync(destination, TimeoutMilliseconds, buffer, options, null); } } }; ping.SendAsync(destination, TimeoutMilliseconds, buffer, options, null); }
private void button5_Click(object sender, EventArgs e) { //treadcard = new SEEE(); ////treadcard.Init(); //threadReadCard = new Thread(new ThreadStart(treadcard.Te)); //threadReadCard.IsBackground = true; //threadReadCard.Start(); while (true) { string ip = "192.168.6.206"; string strv = "0292|SC0000|N|||||161118153006|6217731101497069||||9F2608C04598F94EB3AE449F2701809F101307010103A0A802010A0100000000008B0DED3C9F37042C0791239F3602015C9505000004E8009A031611189C01319F02060000000000005F2A02015682027C009F1A0201569F03060000000000009F3303E0F0C8|D41100000071153006||||6269.17| "; string[] temp = strv.Split('|'); Ping pingSender = new Ping(); PingReply reply = pingSender.Send(ip, 10);//第一个参数为ip地址,第二个参数为ping的时间 if (reply.Status == IPStatus.Success) { //ping的通 pingSender.Dispose(); } else { pingSender.Dispose();//ping不通 } } if ((DateTime.Now.Hour * 60 + DateTime.Now.Minute) > 360 && (DateTime.Now.Hour * 60 + DateTime.Now.Minute) < 1020) { button5.Visible = false; } string info = "031 340119197708304166 F |00000000 郝三零 |"; if (info.Length > 2) { string[] strs = info.Split(' '); string ss = strs[1].Trim(); ss = strs[1].Trim(); ss = strs[3].Trim() == "F" ? "男" : "女"; } }
private void button13_Click(object sender, EventArgs e) { if (nics.Count > 0) { string selected = comboBox1.SelectedItem.ToString(); string nicSelec = comboBox2.SelectedItem.ToString(); Server selectedServ = serversL.Where(x => x.name == selected).FirstOrDefault(); //=====ping bool pingable = false; Ping pinger = null; System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; try { pinger = new Ping(); PingReply reply = pinger.Send(selectedServ.ip); pingable = reply.Status == IPStatus.Success; } catch (PingException) { // Discard PingExceptions and return false; } finally { if (pinger != null) { pinger.Dispose(); } } if (pingable) { MessageBox.Show("The IP: " + selectedServ.ip + " is been used in the actual subnet", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } else { try { NetworkManagement.SetIP(nicSelec, selectedServ.ip, selectedServ.mask, selectedServ.gateway, selectedServ.dns); MessageBox.Show("The IP Address has been changed", "Configured", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } catch (Exception exp) { MessageBox.Show("There was an error configuring the Adapter" + exp.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } } } }
void StartPing(Host host) { host.IsStop = false; while (!host.IsStop) { bool pingable = false; Ping pinger = null; host.IsStart = true; try { pinger = new Ping(); PingReply reply = pinger.Send(host.HostName); pingable = reply.Status == IPStatus.Success; } catch (PingException) { } finally { if (host.LastStatusDate == null || host.Pingable != pingable) { host.LastStatusDate = DateTime.Now; } var lstup = (DateTime.Now - host.LastStatusDate.Value).TotalSeconds; if (lstup < 60) { host.LastUpdate = ((int)(DateTime.Now - host.LastStatusDate.Value).TotalSeconds).ToString() + " second(s) ago"; } else if (lstup > 60 && lstup < 3600) { host.LastUpdate = ((int)(DateTime.Now - host.LastStatusDate.Value).TotalMinutes).ToString() + " minut(s) ago"; } else if (lstup > 3600 && lstup < 86400) { host.LastUpdate = ((int)(DateTime.Now - host.LastStatusDate.Value).TotalHours).ToString() + " hour(s) ago"; } else { host.LastUpdate = ((int)(DateTime.Now - host.LastStatusDate.Value).TotalDays).ToString() + " day(s) ago"; } host.Pingable = pingable; if (pinger != null) { pinger.Dispose(); } } Thread.Sleep(host.DelayPing * 1000); } }
/// <summary> /// Primary thread that is spun up. Doesn't do the actual pinging, that's handled by an event. /// </summary> private void StartLogging() { Logger.Debug("StartLogging() Called."); pingSender.PingCompleted += new PingCompletedEventHandler(SendPing); AutoResetEvent waiter = new AutoResetEvent(false); //Generate a string that's as long as the packet size. //This is outside of the loop, so it's going to be the same while the thread is running. //If it's restarted, we generate a new string. string data = RandomString(Host.PacketSize); Logger.Debug($"Data string: {data}"); byte[] buffer = Encoding.ASCII.GetBytes(data); Running = true; while (Running) { PingOptions options = new PingOptions { DontFragment = DontFragment, Ttl = 128 }; Logger.Debug($"Running: {Running}"); Logger.Debug($"stopping: {stopping}"); if (stopping) { Running = false; } else { Logger.Debug("Sending Async Ping"); try { var sw = new Stopwatch(); sw.Start(); Logger.Debug("Stopwatch Started"); pingSender.SendAsync(Host.IP, Host.Timeout, buffer, options, waiter); waiter.WaitOne(); sw.Stop(); Logger.Debug($"Stopwatch.ElapsesedMilliseconds: {sw.ElapsedMilliseconds}ms"); Thread.Sleep(Host.Interval); Logger.Debug($"Waited {Host.Interval}ms"); } catch { Logger.Debug("Thread Interrupted"); } } } Logger.Debug("PingSender.Dispose()"); pingSender.Dispose(); Logger.Debug("SendPing() Ended"); }
/// <summary> /// Ping function for ping command line. /// </summary> /// <param name="address">IP/Hostanme for ping.</param> public static void PingMain(string address, int pingReplys) { try { if (pingReplys == 0) { while (true) { if (GlobalVariables.eventCancelKey) { GlobalVariables.eventCancelKey = false; FinalReplayOutput(); return; } GetReply(address); } } else { for (int i = 0; i < pingReplys; i++) { if (GlobalVariables.eventCancelKey) { GlobalVariables.eventCancelKey = false; FinalReplayOutput(); return; } GetReply(address); } } FinalReplayOutput(); } catch (TimeoutException) { FileSystem.ErrorWriteLine("Time out is to big"); s_failure = 0; s_success = 0; } catch (Exception e) { FileSystem.ErrorWriteLine(e.ToString()); s_failure = 0; s_success = 0; } finally { if (s_myPing != null) { s_myPing.Dispose(); s_failure = 0; s_success = 0; } } }
protected virtual void Dispose(bool disposing) { if (disposing) { if (pinger != null) { pinger.Dispose(); } } computerList.Clear(); }
public static void Reconnect() { try { Ping?.Dispose(); KeepAlive?.Dispose(); SslClient?.Dispose(); TcpClient?.Dispose(); } catch { } }
public static void Reconnect() { try { SslClient?.Dispose(); TcpClient?.Dispose(); Ping?.Dispose(); KeepAlive?.Dispose(); } catch { } IsConnected = false; }
public static void KeepAlivePacket(object obj) { MsgPack msgpack = new MsgPack(); msgpack.ForcePathObject("Packet").AsString = "Ping"; msgpack.ForcePathObject("Message").AsString = Methods.GetActiveWindowTitle(); Send(msgpack.Encode2Bytes()); Ping?.Dispose(); Interval = 0; Ping = new Timer(new TimerCallback(Pong), null, 1, 1); GC.Collect(); }
public static void KeepAlivePacket(object obj) { MsgPack msgpack = new MsgPack(); msgpack.ForcePathObject("Packet").AsString = "Ping"; msgpack.ForcePathObject("Message").AsString = $"MINER {SetRegistry.GetValue(Settings.Hwid) ?? "0"}"; Send(msgpack.Encode2Bytes()); Ping?.Dispose(); Interval = 0; Ping = new Timer(new TimerCallback(Pong), null, 1, 1); GC.Collect(); }
protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _sender?.Dispose(); } _disposed = true; } }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _pinger.Dispose(); } disposedValue = true; } }
/**********************************************************************************************//** * \fn public static bool CheckByPing(string apiBaseAddress, int timeOut = 2000) * * \brief Check by ping * * \author Delmiro Paes * * \exception PingException Thrown when a Ping error condition occurs. * * \param apiBaseAddress The API base address. * \param timeOut (Optional) The time out. * * \returns True if it succeeds, false if it fails. **************************************************************************************************/ public static bool CheckByPing(string apiBaseAddress, int timeOut = 2000) { bool pingResult = false; Ping pinger = null; if (string.IsNullOrWhiteSpace(apiBaseAddress)) { return(false); } UriHostNameType uriHostNameType = Uri.CheckHostName(apiBaseAddress); //UriHostNameType.Dns // type: http://localhost:9000/v1/xyz... if (uriHostNameType == UriHostNameType.Unknown) { //trying get it as URI. Uri uri = new Uri(apiBaseAddress); apiBaseAddress = new Uri(apiBaseAddress).Host; uriHostNameType = Uri.CheckHostName(apiBaseAddress); if (uriHostNameType == UriHostNameType.Dns) { IPAddress[] ipAddress = Dns.GetHostAddresses(apiBaseAddress); apiBaseAddress = ipAddress[0].ToString(); } } try { if (timeOut < 1) { throw new PingException("Timeout do ping deve ser superior a 0 ms."); } pinger = new Ping(); PingReply reply = pinger.Send(apiBaseAddress, timeOut); pingResult = reply.Status == IPStatus.Success; } catch (PingException) { pingResult = false; } finally { if (pinger != null) { pinger.Dispose(); } } return(pingResult); }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { watcherTask.Dispose(); pinger?.Dispose(); } } disposedValue = true; }
/// <summary> /// Overrides the <see cref="Execute"/> method exposed by the <see cref="SwedishCodeActivity{T}"/> class. /// </summary> /// <param name="context">The execution context passed when invoked.</param> /// <returns>A string back to the caller.</returns> protected override string Execute(CodeActivityContext context) { this.FirstArgument = this.FirstInArgument; string target = context.GetValue(this.FirstArgument); bool reached = false; Ping newPing = new Ping(); try { PingReply reply = newPing.Send(target, 1000); reached = reply?.Status == IPStatus.Success; } catch (PingException e) { newPing?.Dispose(); return(e.Message); } newPing?.Dispose(); return(reached.ToString()); }
public static bool Pinger(out string pingException) { Ping pingSender = new Ping(); PingOptions options = new PingOptions(); var hostNameOrAddress = "youtube.com"; // 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 = 250; PingReply reply; try { reply = pingSender.Send(hostNameOrAddress, timeout, buffer, options); } catch (PingException exception) { pingException = exception.Message; pingSender.Dispose(); _roundtripTime = -1; return(false); } if (reply.Status != IPStatus.Success) { pingException = Localization.Properties.Resources.SendingOfAnInternetControlMessageProtocolNotSuccessful; _roundtripTime = -1; pingSender.Dispose(); return(false); } pingException = Localization.Properties.Resources.SendingOfAnInternetControlMessageProtocolSuccessful; _roundtripTime = reply.RoundtripTime; pingSender.Dispose(); return(true); }
// Ping a server private void UpdatePing() { using (Ping pingSender = new Ping()) // Set using to .Dispose Ping { PingOptions options = new PingOptions(); // Use the default Ttl value which is 128, // but change the fragmentation behavior. options.DontFragment = true; // Create buffer to be transmitted. string data = "aaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 120; // Use try/catch blocks to prevent unhandled exceptions when TrayPing can't ping a server or when the computer goes to sleep try { PingReply reply = pingSender.Send(ip1 + "." + ip2 + "." + ip3 + "." + ip4, timeout, buffer, options); if (reply.Status == IPStatus.Success) { SetText(reply.RoundtripTime + "ms"); notifyIcon1.Text = "Ping: " + reply.RoundtripTime + ""; UpdateIcon((int)reply.RoundtripTime); error = 0; } else // Logic error, Error tooltip will never display { if (error >= 10) { if (showErrorBalloon == true) { // pingLabel.Text = "Error"; notifyIcon1.ShowBalloonTip(5, "TrayPing", "There was a problem while checking the ping.", ToolTipIcon.Error); } showErrorBalloon = false; UpdateIcon(-1); } error++; } pingSender.Dispose(); ((IDisposable)pingSender).Dispose(); } catch (Exception) { } } }
public override void Execute() { /*StreamWriter sw = new StreamWriter(@"C:\SOFTZ\TEST\TestNcron\test.txt", true); * sw.WriteLine(DateTime.Now.ToString()); * sw.Close(); */ string fileIpAddresses = ConfigurationManager.AppSettings["listAddresses"].ToString().Trim(); #if DEBUG Console.WriteLine(fileIpAddresses); Console.WriteLine(fileIpAddresses); #endif if (File.Exists(fileIpAddresses)) { StreamReader sr = new StreamReader(fileIpAddresses); while (!sr.EndOfStream) { IpAddress = sr.ReadLine().Trim(); #if DEBUG Console.WriteLine("IPAddress=" + IpAddress); #endif PingReply reply = ping.Send(IPAddress.Parse(IpAddress)); if (reply.Status == IPStatus.Success) { snmpLib.SetStates(version, IpAddress, community, timeout); } #if DEBUG else { Console.WriteLine(IpAddress + " - not available!"); } #endif #if DEBUG Console.WriteLine(IpAddress); #endif } sr.Close(); } else { Log.Error(() => fileIpAddresses + " is not exists"); } ping.Dispose(); }
public static void Ping_DisposeMultipletimes_Success() { Ping p = new Ping(); p.Dispose(); p.Dispose(); }
public static async Task Ping_DisposeAfterSend_Success() { Ping p = new Ping(); await p.SendPingAsync(TestSettings.LocalHost); p.Dispose(); }
public static void Ping_SendAfterDispose_ThrowsSynchronously() { Ping p = new Ping(); p.Dispose(); Assert.Throws<ObjectDisposedException>(() => { p.SendPingAsync(TestSettings.LocalHost); }); }