private static IPAddress FindBurtsIPAddress(string localIPaddr) { IPAddress burtsIP = localhost; try { System.Net.NetworkInformation.Ping p1 = new System.Net.NetworkInformation.Ping(); try { PR = p1.Send("burt", 250); if (PR.Status.ToString().Equals("Success")) return PR.Address; } catch (Exception e) { }; IPAddress localIP = IPAddress.Parse(localIPaddr); byte[] addrBytes = localIP.GetAddressBytes(); for (byte n = 0; n < 254; n++) { int numBytes = addrBytes.GetLength(0); addrBytes.SetValue(n, numBytes - 1); IPAddress lookupIPAddr = new IPAddress(addrBytes); try { PR = p1.Send(lookupIPAddr, 1000 / 254); if (PR.Status.ToString().Equals("Success")) return PR.Address; } catch (Exception e) { }; if (PR.Status.ToString().Equals("Success")) { Console.WriteLine(PR.Status.ToString()); } } } catch(System.Net.Sockets.SocketException e) { Console.WriteLine("SocketException caught!!!"); Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } catch(Exception e) { Console.WriteLine("Exception caught!!!"); Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } return burtsIP; }
private string sendJson(object jsonrpc) { try { if (string.IsNullOrEmpty(Address)) { return(null); } using (var ping = new System.Net.NetworkInformation.Ping()) { if (ping.Send(Address).Status == System.Net.NetworkInformation.IPStatus.Success) { using (WebClient wc = new WebClient()) { wc.Proxy = null; wc.Headers[HttpRequestHeader.ContentType] = "application/json"; wc.UseDefaultCredentials = true; wc.Credentials = new NetworkCredential(UserName, Password); string json = JsonConvert.SerializeObject(jsonrpc, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); json = WebUtility.UrlEncode(json); return(wc.DownloadString("http://" + Address + "/jsonrpc?request=" + json)); } } } } catch { } return(null); }
private bool ping(string host, int attempts, int timeout) { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingReply; for (int i = 0; i < attempts; i++) { try { pingReply = ping.Send(host, timeout); // If there is a successful ping then return true. if (pingReply != null && pingReply.Status == System.Net.NetworkInformation.IPStatus.Success) { return(true); } } catch { // Do nothing and let it try again until the attempts are exausted. // Exceptions are thrown for normal ping failurs like address lookup // failed. For this reason we are supressing errors. } } // Return false if we can't successfully ping the server after several attempts. return(false); }
public static bool CheckNetwork() { bool res = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pr = null; string host = Properties.Settings.Default.NetPath.ToString().Split('\\')[2]; try { pr = p.Send(host, 1000); switch (pr.Status) { case System.Net.NetworkInformation.IPStatus.Success: res &= true; break; case System.Net.NetworkInformation.IPStatus.TimedOut: res &= false; break; case System.Net.NetworkInformation.IPStatus.DestinationHostUnreachable: res &= false; break; case System.Net.NetworkInformation.IPStatus.Unknown: res &= false; break; default: res &= false; break; } } catch (Exception) { res &= false; } return res; }
/// <summary> /// Pings the provided IP to validate connection /// </summary> /// <returns>True if you are connected</returns> /// <history> /// [Tim Hibbard] 01/24/2007 Created /// </history> public bool TestConnection() { bool RV = false; _isChecking = true; try { OnPinging(); System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); if (ping.Send(_IPToPing).Status == System.Net.NetworkInformation.IPStatus.Success) { RV = true; } else { RV = false; } ping = null; if (RV != _isConnected) { _isConnected = RV; OnConnectionStatusChanged(_isConnected); } OnIdle(); } catch (Exception Ex) { Debug.Assert(false, Ex.ToString()); RV = false; OnIdle(); } _isChecking = false; return(RV); }
private bool pingSite(string url_toTest) { var ping = new System.Net.NetworkInformation.Ping(); try { var result = ping.Send(url_toTest); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) { this.form.error("Error : Can't reach Github."); return(false); } else { return(true); } } catch (Exception ex) { this.form.error( "Can't reach Github.\n" + "Error : \n" + "\"" + ex.Message + "\"" ); return(false); } }
private static bool IsServerConnected(string connectionString) { using (SqlConnection connection = new SqlConnection(connectionString)) { try { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply reply = p.Send(connection.DataSource); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { connection.Open(); return(true); } else { return(false); } } catch (SqlException err) { MessageBox.Show(err.Message); return(false); } } }
public static bool Send(string url, out System.Net.NetworkInformation.PingReply reply) { reply = null; using (System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping()) { try { reply = pingSender.Send(url); if (reply?.Status != System.Net.NetworkInformation.IPStatus.Success) { return(false); //Console.WriteLine("Address: {0}", reply.Address.ToString()); //Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime); //Console.WriteLine("Time to live: {0}", reply.Options.Ttl); //Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment); //Console.WriteLine("Buffer size: {0}", reply.Buffer.Length); } return(true); } // ReSharper disable once UnusedVariable catch (Exception ex) { Logger.Instance.AppendException(ex); // ReSharper disable once RedundantJumpStatement return(false); } } }
public void Run() { hostPlayer = null; List <PlayerPingPair> hostables = new List <PlayerPingPair>(); System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); foreach (MNPlayer player in players) { if (player.canHost) { var pair = new PlayerPingPair(player); var reply = ping.Send(MNListServer.Instance.GetProperAddress(player)); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { pair.ping = reply.RoundtripTime; } hostables.Add(pair); } } ping.Dispose(); if (hostables.Count <= 0) { return; } PlayerPingPair best = hostables[0]; foreach (PlayerPingPair pair in hostables) { if (best.ping > pair.ping) { best = pair; } } hostPlayer = best.player; }
/// <summary> /// 通过Ping命令测试仪器是否开机 /// <param name="ipAddress">IP地址</param> /// <param name="timeout">timeout时间(毫秒)</param> /// </summary> public static bool PingDevice(string ipAddress, int timeout) { //通过Ping命令测试仪器是否开机 System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "Test!"; byte[] buffer = Encoding.ASCII.GetBytes(data); ErrorString = null; try { System.Net.NetworkInformation.PingReply reply = p.Send(ipAddress, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) //能够Ping通,返回True { return(true); } else { return(false); } } catch (Exception) { return(false); } }
public void UpdateData() { if (_data.Count > 0 && (DateTime.Now - _lastUpdateTime).TotalMinutes < 1) return; lock (_lockObj) { if ((DateTime.Now - _lastUpdateTime).TotalMinutes < 1) return; new Thread(() => { _data = GetList(); foreach (var ip in _data) { var ping = new System.Net.NetworkInformation.Ping(); var reply = ping.Send(ip.IPAddress, 1000 * 10); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { ip.Ping = reply.RoundtripTime; } } _data = _data.OrderBy(e => e.Ping).ToList(); _lastUpdateTime = DateTime.Now; }).Start(); } }
private bool InitialChecks() { try { lblCurrentTask.Text = "Initial checks.."; System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); var result = ping.Send("vp-db.vestas.net"); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) { ShowErrorBox("Could not ping vp-db.vestas.net, are you connected on VPN or in a office?", ""); return(false); } } catch (System.Net.NetworkInformation.PingException ex) { ShowErrorBox("Could not lookup DNS: vp-db.vestas.net, are you connected to the Vestas network?", ""); return(false); } catch (Exception ex) { ShowErrorBox("Initial checks failed", ex.Message); return(false); } return(true); }
private void PingTerminal() { bool result = false; string exceptionMessage = null; try { using (System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping()) { System.Net.NetworkInformation.PingReply pingReply = ping.Send(Program.m_sSmartpayIP); result = (pingReply.Status == System.Net.NetworkInformation.IPStatus.Success); } } catch (Exception ex) { exceptionMessage = ex.Message; } MessageBox.Show(result.ToString()); /* * MessageBox.Show( * this, * String.Format( * "Result: {0}" + Environment.NewLine + * "Additional Info: {1}", * result ? "Success" : "Failed", * exceptionMessage ?? "None"), * "Name", * MessageBoxButtons.OK, * MessageBoxIcon.Information); */ }
public static bool TestConnection() { VPN vpn = new VPN(); bool RV = false; try { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); if (ping.Send(vpn.IPToPing).Status == System.Net.NetworkInformation.IPStatus.Success) { RV = true; } else { RV = false; } ping = null; } catch (Exception Ex) { Debug.Assert(false, Ex.ToString()); RV = false; } return(RV); }
/// <summary></summary> protected override bool online() { //Determine online status bool online = false; try { string dbserver = ""; string connection = base.mConnection; string[] tokens = connection.Split(';'); foreach (string token in tokens) { if (token.Contains("data source=")) { dbserver = token.Substring(token.IndexOf("=") + 1); break; } } System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); if (ping.Send(dbserver, Mediator.PingTimeout).Status == System.Net.NetworkInformation.IPStatus.Success) { online = true; } } catch { } return(online); }
//static async void CallMethod() //{ // await InternetVarmi2(); // //InternetVarmi2(); //} public bool InternetVarmi2() { try { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingDurumu = ping.Send("www.google.com");//IPAddress.Parse("64.15.112.45")); if (pingDurumu.Status == System.Net.NetworkInformation.IPStatus.Success) { ivarmi = true; return(true); //Console.WriteLine("İnternet bağlantısı var"); } else { ivarmi = false; return(false); //Console.WriteLine("İnternet bağlantısı yok"); } //Console.ReadKey(); //return true; } catch { ivarmi = false; return(false); } }
/// <summary> /// Filter Unusable ip /// </summary> /// <param name="ip"></param> /// <returns></returns> public static bool ValidateProxy(string ip, int port) { bool result = false; System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); IPAddress ipAddress = IPAddress.Parse(ip); var replay = pingSender.Send(ipAddress, 1500);//set timeout time if (replay.Status == System.Net.NetworkInformation.IPStatus.Success) { try { IPEndPoint point = new IPEndPoint(ipAddress, port); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(point); //可用的Proxy result = true; } catch (Exception) { result = false; } } return(result); }
/// <summary> /// Описание нашей системы /// </summary> public void DescribeSystem() { Console.Title = "Сканер локальной сети"; Console.CursorVisible = false; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\n---------------------------------Этот компьютер---------------------------------"); //-----------------------------------------Проверка соединения с интернетом------------------------------------------------------- string proverka_soedineniya_s_internetom1 = ""; try { System.Net.NetworkInformation.Ping proverka_pinga = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply proverka_pingReply1 = proverka_pinga.Send("google.com"); proverka_soedineniya_s_internetom1 = proverka_pingReply1.Status.ToString(); if (proverka_soedineniya_s_internetom1 == "Success") { proverka_soedineniya_s_internetom1 = "Соединение присутствует"; } else { proverka_soedineniya_s_internetom1 = "Соединение отсутствует"; } } catch { proverka_soedineniya_s_internetom1 = "Соединение отсутствует"; } //-------------------------------------------------------------------------------------------------------------------------------- Console.WriteLine("Имя компьютера: " + host + "\t\tСостояние подключения к интернету:"); Console.WriteLine("IP-адрес компьютера: " + ip_addres + "\t" + proverka_soedineniya_s_internetom1); Console.WriteLine("\n--------------------------------------------------------------------------------"); }
private void btnServer_Click(object sender, EventArgs e) { cmbDatabase.Properties.Items.Clear(); bool state = false; try { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); if (ping.Send(txtServer.Text).Status == System.Net.NetworkInformation.IPStatus.Success) { state = true; } } catch (Exception ex) { MessageErrorDialog error = new MessageErrorDialog("Destinacija!?", "Ping destinacije nije uspio! Provjerite IP.", ex.ToString()); error.ShowDialog(); } if (state) { //Helpers.Reader.GetDatabases(ref cmbDatabase, cmbServer, txtLogin.Text, txtPassword.Text); Helpers.Reader.GetDestDatabases(ref cmbDatabase, txtServer.Text, txtLogin.Text, txtPassword.Text); btnServer.Text = "VPN ok!"; btnServer.Appearance.BackColor = Color.DarkSeaGreen; } else { btnServer.Text = "VPN??"; btnServer.Appearance.BackColor = Color.IndianRed; } }
private static string GetActiveUrl(string[] address) { HttpWebRequest webRequest = null; try { foreach (var item in address) { webRequest = (HttpWebRequest)WebRequest.Create(item); var ping = new System.Net.NetworkInformation.Ping(); var reply = ping.Send(webRequest.Address.Host, 3000); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { return(item); } } throw new Exception("No Active IP adddress found, make sure network IP is correct and conneted to the right network."); } catch (Exception) { return(null); } }
protected void PingTest(CancellationToken token) { System.Net.NetworkInformation.Ping pingClass = new System.Net.NetworkInformation.Ping(); while (token.IsCancellationRequested == false) { System.Net.NetworkInformation.PingReply pingReply = pingClass.Send(IPAddress); //if ip is valid run checks else if (pingReply.Status == System.Net.NetworkInformation.IPStatus.Success) { if (IsOnline != true) { IsOnline = true; Log(log.Info, "{0} is online!", IPAddress.ToString()); RaiseOnlineChanged(EventArgs.Empty); } } else { if (IsOnline == true) { IsOnline = false; Log(log.Info, "{0} has gone offline!", IPAddress.ToString()); RaiseOnlineChanged(EventArgs.Empty); } } Thread.Sleep(5000); } }
static long ResponseTime(string url) { var ping = new System.Net.NetworkInformation.Ping(); List <long> times = new List <long> { }; for (int i = 0; i < 5; i++) { try { var result = ping.Send(url); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) { return(-1); } else { times.Add(result.RoundtripTime); } } catch { return(-1); } } return(times.Min()); }
/// <summary> /// 利用Ping方法确定是否可以通过网络访问远程计算机 /// </summary> /// <param name="status">网络状态</param> /// <param name="ipAddressOrHostName">默认是www.baidu.com</param> /// <param name="timeout">默认是1000毫秒</param> /// <returns></returns> public static bool PingIsConnectedInternet(out System.Net.NetworkInformation.IPStatus status, string ipAddressOrHostName = "www.baidu.com", int timeout = 1000) { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "aa"; byte[] buffer = Encoding.ASCII.GetBytes(data); //Wait seconds for a reply. status = System.Net.NetworkInformation.IPStatus.Unknown; try { System.Net.NetworkInformation.PingReply reply = p.Send(ipAddressOrHostName, timeout, buffer, options); status = reply.Status; if (status == System.Net.NetworkInformation.IPStatus.Success) { return(true); } else { return(false); } } catch { return(false); } }
private void carRateToMysql() { while (getTotalCarNumone() != 0 && getTotalCarNumtwo() != 0) { ratetotal = (double)getTotalOkCarNum() / getTotalCarNum(); rateone = (double)getTotalOkCarNumone() / getTotalCarNumone(); ratetwo = (double)getTotalOkCarNumtwo() / getTotalCarNumtwo(); string sql = "insert into finalcarinfo values('" + DateTime.Now.ToString() + "','" + getTotalCarNum() + "','" + ratetotal.ToString("0.00%") + "','" + getTotalCarNumone() + "','" + rateone.ToString("0.00%") + "','" + getTotalCarNumtwo() + "','" + ratetwo.ToString("0.00%") + "')"; string sqldel = "delete from finalcarinfo"; //检测网络连接状态,网络连接成功后,写入数据 System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingStatus = ping.Send(IPAddress.Parse("202.108.22.5"), 1000);//ping 百度的IP地址 if (pingStatus.Status == System.Net.NetworkInformation.IPStatus.Success) { sqlOperate.MySqlCom(sqldel); sqlOperate.MySqlCom(sql); } Thread.Sleep(300000); } }
public bool Ping(string ip) { try { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "Test Data!"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 1000; // Timeout 时间,单位:毫秒 System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { return(true); } else { return(false); } } catch { return(false); } }
private void ovenInfoToAliMysql() { while (true) { Thread.Sleep(600000); chimneyTem[0] = Convert.ToString(operatePlc.readPlcDbdValues("10.228.140.46", 0, 3, 92, 0)); chimneyTem[1] = Convert.ToString(operatePlc.readPlcDbdValues("10.228.140.54", 0, 3, 92, 0)); chimneyTem[2] = Convert.ToString(operatePlc.readPlcDbdValues("10.228.140.98", 0, 3, 92, 0)); chimneyTem[3] = Convert.ToString(operatePlc.readPlcDbdValues("10.228.141.38", 0, 3, 92, 0)); chimneyTem[4] = Convert.ToString(operatePlc.readPlcDbdValues("10.228.141.46", 0, 3, 92, 0)); chimneyTem[5] = Convert.ToString(operatePlc.readPlcDbdValues("10.228.141.82", 0, 3, 92, 0)); chimneyTem[6] = Convert.ToString(operatePlc.readPlcDbdValues("10.228.141.126", 0, 3, 92, 0)); tnvTem[0] = Convert.ToString(operatePlc.readPlcDbwValue("10.228.140.46", 0, 3, 294, 2)); tnvTem[1] = Convert.ToString(operatePlc.readPlcDbwValue("10.228.140.54", 0, 3, 294, 2)); tnvTem[2] = Convert.ToString(operatePlc.readPlcDbwValue("10.228.140.98", 0, 3, 294, 2)); tnvTem[3] = Convert.ToString(operatePlc.readPlcDbwValue("10.228.141.38", 0, 3, 294, 2)); tnvTem[4] = Convert.ToString(operatePlc.readPlcDbwValue("10.228.141.46", 0, 3, 294, 2)); tnvTem[5] = Convert.ToString(operatePlc.readPlcDbwValue("10.228.141.82", 0, 3, 294, 2)); tnvTem[6] = Convert.ToString(operatePlc.readPlcDbwValue("10.228.141.126", 0, 3, 294, 2)); string sql = "insert into oveninfo (DA,ED1TNV,ED1CHIMNEY,ED2TNV,ED2CHIMNEY,PVCTNV,PVCCHIMNEY,PR1TNV,PR1CHIMNEY,PR2TNV,PR2CHIMNEY,TC1TNV,TC1CHIMNEY,TC2TNV,TC2CHIMNEY) values('" + DateTime.Now.ToString() + "','" + chimneyTem[0] + "','" + chimneyTem[1] + "','" + chimneyTem[2] + "','" + chimneyTem[3] + "','" + chimneyTem[4] + "','" + chimneyTem[5] + "','" + chimneyTem[6] + "','" + tnvTem[0] + "','" + tnvTem[1] + "','" + tnvTem[2] + "','" + tnvTem[3] + "','" + tnvTem[4] + "','" + tnvTem[5] + "','" + tnvTem[6] + "')"; //检测网络连接状态,网络连接成功后,写入数据 System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingStatus = ping.Send(IPAddress.Parse("202.108.22.5"), 1000);//ping 百度的IP地址 if (pingStatus.Status == System.Net.NetworkInformation.IPStatus.Success) { sqlOperate.MySqlCom(sql); } } }
private void CheckHostAvailablity() { System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.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; System.Net.NetworkInformation.PingReply reply; try { reply = pingSender.Send(Properties.Settings.Default.SiteUrl, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { MainViewModel.Instance.HostAvailable = true; } else { MainViewModel.Instance.HostAvailable = false; } } catch (System.Net.NetworkInformation.PingException) { MainViewModel.Instance.HostAvailable = false; } }
public static bool Ping(string ip) { try { using (System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping()) { System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "MissionPlanner"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 500; System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { return(true); } else { return(false); } } } catch { return(false); } }
/// <summary> /// Ping命令检测网络是否畅通 /// </summary> /// <param name="urls">URL数据</param> /// <returns></returns> public static bool PingInternet(string[] urls) { bool isconn = true; System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); int errorCount = 0; try { System.Net.NetworkInformation.PingReply pr; for (int i = 0; i < urls.Length; i++) { pr = ping.Send(urls[i]); if (pr.Status != System.Net.NetworkInformation.IPStatus.Success) { isconn = false; errorCount++; } } } catch { isconn = false; errorCount = urls.Length; } return(isconn); }
public static bool getNetStatus() { System.Net.NetworkInformation.Ping ping; System.Net.NetworkInformation.PingReply ret; ping = new System.Net.NetworkInformation.Ping(); try { ret = ping.Send("www.baidu.com"); if (ret.Status != System.Net.NetworkInformation.IPStatus.Success) { //没网 return(false); } else { //有网 return(true); } } catch (Exception err) { // MessageBox.Show("获取网络状态异常:" + err.ToString()); //MessageBox.Show("获取网络状态异常"); return(false); } }
public static bool pingHost(string host) { if (!String.IsNullOrEmpty(host)) { try { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingReply = ping.Send(host); return true; } catch (System.Net.NetworkInformation.PingException e) { //MessageBox.Show(e.Message); return false; } } else { return false; } }
public bool Ping(string Address, int Timeout) { if (Address == null) { return(false); } Address = Address.Trim(); if ((Address == "") || (Timeout < 1)) { return(false); } Options.DontFragment = true; try { Reply = Pinger.Send(Address, Timeout, Packet, Options); } catch (System.Exception Excpt) { Err.Add(Excpt); return(false); } if (Reply.Status != System.Net.NetworkInformation.IPStatus.Success) { return(false); } else { return(true); } }
public void UpdateData() { if (_data.Count > 0 && (DateTime.Now - _lastUpdateTime).TotalMinutes < 1) { return; } lock (_lockObj) { if ((DateTime.Now - _lastUpdateTime).TotalMinutes < 1) { return; } new Thread(() => { _data = GetList(); foreach (var ip in _data) { var ping = new System.Net.NetworkInformation.Ping(); var reply = ping.Send(ip.IPAddress, 1000 * 10); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { ip.Ping = reply.RoundtripTime; } } _data = _data.OrderBy(e => e.Ping).ToList(); _lastUpdateTime = DateTime.Now; }).Start(); } }
/// <summary> /// 检查IP网络连接 /// </summary> /// <param name="IpOrName">IP地址/域名</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static bool CheckIP(string IpOrName, int timeOut) { if (IpOrName == null) { return false; } if (IpOrName == ".") { IpOrName = "127.0.0.1"; } System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingReplay = null; try { pingReplay = ping.Send(IpOrName, timeOut); } catch { return false; } return pingReplay.Status.ToString().Equals("Success"); }
public bool CheckNetworkConnection(string IP) { if (string.IsNullOrEmpty(IP)) { return(false); } try { System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(IP); System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply reply; reply = pinger.Send(ipAddress, Convert.ToInt32(txtPingTimeout.Text)); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { return(true); } else { return(false); } } catch (Exception) { return(false); } }
private Boolean ValidateURI(string _uri) { var ping = new System.Net.NetworkInformation.Ping(); var result = ping.Send(_uri); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) return true; return false; }
public static string CheckConfigSettings() { string ret = ""; string c = GetHostVmPath(); if (!(c.EndsWith("/") || c.EndsWith("\\"))) ret += "HostVMPath should end with / or \\<br />"; c = GetDatastore(); if (!(c.Contains("] ") && (c.Contains("[")))) ret += "Datastore should contain [ and ] (with trailing space)<br />"; ret+=CheckPath(GetWebserverVmPath(),"WebserverVmPath"); ret += CheckPath(GetWebserverTmpPath(), "WebserverTmpPath"); ret += CheckPath(GetWebserverBaseImagePath(), "WebserverBaseImagePath"); c = GetNetworkInterfaceName(); if (c.Length < 6) ret += "Network Interface Name too short<br />"; c = GetVMwareHostAndPort(); if (c.Contains(":")) { var p = new System.Net.NetworkInformation.Ping(); try { p.Send(GetVMHostName(), 10000); } catch (Exception e) { ret += "couldn't ping VMwareHost, exception: " + e.Message+"<br />"; } } else ret += "VMwareHostAndPort must contain hostname and port, seperated by colon<br />"; try { RegisteredVirtualMachineService.GetVirtualHost(); } catch (Exception e) { ret += "can't connect to VMware Server. Check hostname, username, password. Exception: "+e.Message+"<br />"; } //usernames, passwords, GetDataFilesDirectory skipped if (ret.Length < 2) { ret += "Web.config settings check succeeded, no errors found.<br />"; } else { ret += "<br />Web.config settings check failed, errors listed above.<br />"; } return ret; }
static bool pingIP(string IP) { var ping = new System.Net.NetworkInformation.Ping(); var result = ping.Send(IP); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) { return false; } return true; }
/// <summary> /// Ping /// </summary> /// <param name="Address"></param> /// <param name="Timeout"></param> public static void Ping(string Address, int Timeout) { using (System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping()) { if (Timeout == 0) Timeout = 5000; if (p.Send(Address, Timeout).Status != System.Net.NetworkInformation.IPStatus.Success) { throw new Exception("Ping " + Address + " Error"); } } }
private void button1_Click(object sender, EventArgs e) { //Adevarat = 1; System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply prep; string url = "10.10.0.32"; prep = p.Send(url); if (prep.Status == System.Net.NetworkInformation.IPStatus.Success) { string address = prep.Address.ToString(); string time = prep.RoundtripTime.ToString(); Adevarat = 1; // MessageBox.Show("ping successfull" + "machine address :" + address + "Round trip time" + time); } else { string status = prep.Status.ToString(); MessageBox.Show("not successfull" + status); } string url1 = "http://"+url+"/Razvan"+"?"+"username="******"&password="******"http://" + url + "/Razvan" + "?" + "username="******"&password="******"Moloz pe tava"); } //MessageBox.Show(url1, "A"); if (Adevarat == 0) textBox2.Text = "Neconectat"; else { textBox2.Text = "Connected"; Form2 m = new Form2(); m.Show(); Form1 f = new Form1(); this.Visible = false; this.Hide(); } // MessageBox.Show(Username , "A"); // MessageBox.Show(Password, "B"); }
/// <summary> /// Ping ��ͨ���׳��쳣 /// </summary> /// <param name="Address"></param> /// <param name="Timeout"></param> /// <returns></returns> public static bool PingWithoutException(string Address, int Timeout) { using (System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping()) { if (Timeout == 0) Timeout = 5000; if (p.Send(Address, Timeout).Status != System.Net.NetworkInformation.IPStatus.Success) { return false; } } return true; }
public static void checkNet() { try { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pr = p.Send("www.google.com"); if (pr.Status == System.Net.NetworkInformation.IPStatus.Success) { return; } System.Windows.Forms.MessageBox.Show("請檢查網路連線."); return; } catch { System.Windows.Forms.MessageBox.Show("請檢查網路連線."); return; } }
public bool Ping(string ip) { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "Test Data!"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 1000; // Timeout 时间,单位:毫秒 System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) return true; else return false; }
public static bool IsServerRunning(string ipAddress) { if (ipAddress.Trim() == "") return false; bool isRunning = false; //check ip address System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingReply = pinger.Send(ipAddress); if (pingReply.Status != System.Net.NetworkInformation.IPStatus.Success) { throw new Exception("Server could not be connected."); } //check service BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider(); provider.TypeFilterLevel = TypeFilterLevel.Full; // Creating the IDictionary to set the port on the channel instance. IDictionary props = new Hashtable(); props["port"] = Properties.Settings.Default.TestPort; props["name"] = "Test" + DateTime.Now.Ticks.ToString(); TcpChannel channel = new TcpChannel(props, null, provider); ChannelServices.RegisterChannel(channel, false); int serverPort = Properties.Settings.Default.ServerPort; string serviceName = Properties.Settings.Default.ServiceName; Type lookupType = typeof(IDataController); IDataController serv = (IDataController)Activator.GetObject(lookupType, string.Format("tcp://{0}:{1}/{2}", ipAddress, serverPort, serviceName)); try { serv.TestDataController(new Holiday()); isRunning = true; } catch { isRunning = false; } finally { ChannelServices.UnregisterChannel(channel); } return isRunning; }
public PingLineViewModel Ping() { Thread.Sleep(TimeSpan.FromSeconds(1).Milliseconds); var ping = new System.Net.NetworkInformation.Ping(); var reply = ping.Send(Host); var viewModel = new PingLineViewModel ( bytes: Bytes, host: Host, reply: reply ); return viewModel; }
public void checkNet() { try { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pr = p.Send("www.google.com"); if(pr.Status == System.Net.NetworkInformation.IPStatus.Success) { return; } System.Windows.Forms.MessageBox.Show("Please Check Your Internet Status."); System.Windows.Forms.Application.Exit(); } catch { System.Windows.Forms.MessageBox.Show("Unknown Error."); System.Windows.Forms.Application.Exit(); } }
public bool PingTest(string Ip) { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingStatus = ping.Send(IPAddress.Parse(Ip), 1000); if (pingStatus.Status == System.Net.NetworkInformation.IPStatus.Success) { return true; } else { return false; } }
private static bool slaveOnline(string victim) { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); try { System.Net.NetworkInformation.PingReply reply = ping.Send(victim); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { return true; } } catch (System.Net.NetworkInformation.PingException) { return false; } return false; }
static bool pingHostName(string HostName) { var ping = new System.Net.NetworkInformation.Ping(); try { var result = ping.Send(HostName); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) { return false; } } catch { return false; } return true; }
public static void checkNet() { System.Net.NetworkInformation.Ping hi = new System.Net.NetworkInformation.Ping(); try { if (hi.Send("www.google.com").Status == System.Net.NetworkInformation.IPStatus.Success) { return; } else { System.Windows.Forms.MessageBox.Show("Please check your Internet."); } } catch { System.Windows.Forms.MessageBox.Show("Unknown Errors."); } }
void StreamStoppedcallback(Twitterizer.Streaming.StopReasons stopreason) { //What happen??!??!?!??!!??!1//1/1/111oneone //Restart dat SHEET OF PAPER //System.Threading.Thread.Sleep(2000); wat TwitterStatus notification = new TwitterStatus(); notification.Text = "Stream died! Restarting stream when twitter is aviable again..."; notification.User = new TwitterUser(); notification.User.ScreenName = "Internal message system"; NewTweet(notification, privOAuth); bool offline = true; while (offline) { bool isOnline = false; try { System.Net.NetworkInformation.Ping pong = new System.Net.NetworkInformation.Ping(); IPAddress adress = new IPAddress(new byte[] {8,8,8,8}); if (pong.Send(adress).Status == System.Net.NetworkInformation.IPStatus.Success) { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply result = ping.Send("www.twitter.com"); if (result.Status == System.Net.NetworkInformation.IPStatus.Success) { isOnline = true; } } } catch(Exception){} if (isOnline) { offline = false; } else { System.Threading.Thread.Sleep(10000); } } notification = new TwitterStatus(); notification.Text = "Restarting stream!"; notification.User = new TwitterUser(); notification.User.ScreenName = "Internal message system"; NewTweet(notification, privOAuth); System.Threading.Thread.Sleep(500); clear("connection lost"); FetchTweets(privOAuth); StartStream(new Twitterizer.Streaming.StreamOptions()); }
//This function is for testing a node on the network private void testConnection(object sender, System.ComponentModel.DoWorkEventArgs e) { //listbox.TopIndex = listbox.Items.Count - 1; listBox1.Invoke(new Action(() => listBox1.Items.Add(" Start! "))); //bool to determin if the while loop has run once for things I want to do ONE time bool checkedOS = true; string osVersion = null; int maxMem = 104857600; int pingTimeOut = -1; bool canConnect = false; while (true) { //Check to see if the worker has been cancled. if (worker.CancellationPending == true) { worker.Dispose(); return; } //This is to warn if the program is eating up TOO much memory, 50MB is the warning. if(System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 >= maxMem) { string answerToContinue = MessageBox.Show("Warning, the application is taking up 100MB or more, would you like to continue? If you say yes then the error will show again at " + maxMem + " bytes", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation).ToString(); if(answerToContinue == "No") { stopButton_Click(); return; } else { maxMem = maxMem * 2; } //Null item answerToContinue = null; } //Do this once if check OS is checked if (checkedOS == true && attemptOSVersion.Checked == true) { osVersion = GetOsVersion(ipAddressBox.Text); checkedOS = false; } //Check to see if they want auto scroll, if so then scroll if(autoScroll.Checked == true) { listBox1.Invoke(new Action(() => listBox1.TopIndex = listBox1.Items.Count - 1)); } //Get ping info string pingInfo = ""; string pingTTL = ""; System.Net.IPAddress hostIP = null; //bool to stop continuing ping if host cannot be converted to IP if (ipAddressBox.Text != "") { try { System.Net.NetworkInformation.Ping myPing = new System.Net.NetworkInformation.Ping(); String host = null; if (forceIPv4 == true) { host = Array.FindAll(System.Net.Dns.GetHostEntry(ipAddressBox.Text).AddressList, a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)[0].ToString(); } else { host = ipAddressBox.Text; } byte[] buffer = new byte[32]; System.Net.NetworkInformation.PingOptions pingOptions = new System.Net.NetworkInformation.PingOptions(); System.Net.NetworkInformation.PingReply reply = null; try { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); reply = myPing.Send(host, 1000, buffer, pingOptions); stopwatch.Stop(); pingTimeOut = stopwatch.Elapsed.Milliseconds; hostIP = reply.Address; } catch(Exception) { //MessageBox.Show("Error sending ping: " + ex.Message); listBox1.Invoke(new Action(() => listBox1.Items.Add("Cannot find IP address of the hostname: " + ipAddressBox.Text))); canConnect = false; } if (/*reply != null &&*/ reply.Status.ToString().Contains("Success")) { canConnect = true; //IPv6 doesn't have TTL, check for that if(/*pingTTL == null*/ reply.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { pingTTL = null; } else { pingTTL = reply.Options.Ttl.ToString(); } pingInfo = reply.RoundtripTime.ToString(); //MessageBox.Show(pingInfo); } } catch (Exception) { //Failed to get host or ping } } else { canConnect = false; } if (canConnect == true) { if (showFailsOnly.Checked == false) { //This is what's printed to the screen //invoke because this is in another thread! try { this.Invoke(new Action(() => this.BackColor = System.Drawing.Color.Green)); } catch (Exception) { } listBox1.Invoke(new Action(() => listBox1.Items.Add("IP Address: " + hostIP))); listBox1.Invoke(new Action(() => listBox1.Items.Add(DateTime.Now + " " + (ipAddressBox.Text) + " is " + "UP"))); listBox1.Invoke(new Action(() => listBox1.Items.Add("Round Trip Time: " + pingInfo))); if (pingTimeOut >= 0) { listBox1.Invoke(new Action(() => listBox1.Items.Add(pingTimeOut.ToString() + " milliseconds"))); } try { if (pingTTL != null || hostIP.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) { listBox1.Invoke(new Action(() => listBox1.Items.Add("TTL: " + pingTTL))); } } catch (Exception) { // } //Get OS Version info if the user selects it if (attemptOSVersion.Checked == true) { if (osVersion != null) { listBox1.Invoke(new Action(() => listBox1.Items.Add("OS: " + osVersion))); } } listBox1.Invoke(new Action(() => listBox1.Items.Add(" "))); //Set max timeout if(Convert.ToInt32(maxTimeOutCounter.Text) < pingTimeOut) { maxTimeOutCounter.Invoke(new Action(() => maxTimeOutCounter.Text = pingTimeOut.ToString())); } } //Tick Succsess succeedCounter.Invoke(new Action(() => succeedCounter.Text = (Convert.ToInt32(succeedCounter.Text) + 1).ToString() )); } else { this.Invoke(new Action(() => this.BackColor = System.Drawing.Color.Red)); //invoke because this is in another thread! listBox1.Invoke(new Action(() => listBox1.Items.Add("IP Address: " + hostIP))); listBox1.Invoke(new Action(() => listBox1.Items.Add(DateTime.Now + " " + (ipAddressBox.Text) + " is " + "DOWN"))); listBox1.Invoke(new Action(() => listBox1.Items.Add(" "))); //Tick fail failCounter.Invoke(new Action(() => failCounter.Text = (Convert.ToInt32(failCounter.Text) + 1).ToString())); } //timeout //Get the reliability, succseed / total reliabilityCounter.Invoke(new Action(() => reliabilityCounter.Text = Math.Round((Convert.ToDouble(succeedCounter.Text) / (Convert.ToDouble(succeedCounter.Text) + Convert.ToDouble(failCounter.Text))) * 100, 2).ToString() + "%")); //update chart updateChart(); if(userWaitTime != 0) { System.Threading.Thread.Sleep(userWaitTime * 1000); } GC.Collect(); } }
public bool isSitePingable(string serverURL) { var ping = new System.Net.NetworkInformation.Ping(); var result = ping.Send(serverURL); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) return false; else return true; }
public string GetOsVersion(string ipAddress) { if(ipAddressBox.Text == "") { return "ADDRESS EMPTY"; } System.Net.NetworkInformation.Ping myPing = new System.Net.NetworkInformation.Ping(); String host = ipAddressBox.Text; byte[] buffer = new byte[32]; //MessageBox.Show(timeout.ToString()); System.Net.NetworkInformation.PingOptions pingOptions = new System.Net.NetworkInformation.PingOptions(); System.Net.NetworkInformation.PingReply reply; try { reply = myPing.Send(host, 1000, buffer, pingOptions); } catch (Exception ex) { //FIX!! return ex.Message; } //Null out variables not needed myPing = null; host = null; buffer = null; pingOptions = null; int pingTTL = reply.Options.Ttl; reply = null; GC.Collect(); //Only attempt this if it's a Windows host if (pingTTL <= 128 && pingTTL > 64) { try { //This will display the message to the user letting them know the program is getting the OS listBox1.Items.Add("Trying to get OS information, this may take a second or two"); //Check to see if the port is open before you access the registry, if not the .NET API will freeze and sometimes crash using (var reg = Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, ipAddress)) using (var key = reg.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\")) { return string.Format("Name:{0}, Version:{1}", key.GetValue("ProductName"), key.GetValue("CurrentVersion")); } } catch(Exception) { return "Windows"; } } else if (pingTTL <= 64) { return "Linux"; } else if (pingTTL <= 255 && pingTTL >= 129) { return "Unix"; } else { return "Error getting OS"; } }
static bool pingURL(string URL) { Uri url = new Uri(URL); string pingurl = string.Format("{0}", url.Host); string host = pingurl; bool result = false; var IPStatus = new System.Net.NetworkInformation.IPStatus(); var p = new System.Net.NetworkInformation.Ping(); try { var reply = p.Send(host, 3000); if (reply.Status == IPStatus) return true; } catch { } return result; }
/// <summary> /// Filter Unusable ip /// </summary> /// <param name="ip"></param> /// <returns></returns> public static bool ValidateProxy(string ip) { bool result = false; System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); IPAddress ipAddress = IPAddress.Parse(ip); var replay = pingSender.Send(ipAddress, 1500);//set timeout time if (replay.Status == System.Net.NetworkInformation.IPStatus.Success) { //可用的Proxy result = true; } return result; }
public static bool Ping(string ip) { try { using (System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping()) { System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "MissionPlanner"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 500; System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) return true; else return false; } } catch { return false; } }
/// <summary> /// Pings the provided IP to validate connection /// </summary> /// <returns>True if you are connected</returns> /// <history> /// [Tim Hibbard] 01/24/2007 Created /// </history> public bool TestConnection() { bool RV = false; _isChecking = true; try { OnPinging(); System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); if (ping.Send(_IPToPing).Status == System.Net.NetworkInformation.IPStatus.Success) { RV = true; } else { RV = false; } ping = null; if (RV != _isConnected) { _isConnected = RV; OnConnectionStatusChanged(_isConnected); } OnIdle(); } catch (Exception Ex) { Debug.Assert(false, Ex.ToString()); RV = false; OnIdle(); } _isChecking = false; return RV; }
private static bool IsDriveReady(string serverName) { // *** SET YOUR TIMEOUT HERE *** int timeout = 5; // 5 seconds System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; // Enter a valid ip address string ipAddressOrHostName = serverName; string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = System.Text.Encoding.ASCII.GetBytes(data); System.Net.NetworkInformation.PingReply reply = pingSender.Send(ipAddressOrHostName, timeout, buffer, options); return (reply.Status == System.Net.NetworkInformation.IPStatus.Success); }
//Traceroute inspired by: http://coding.infoconex.com/post/C-Traceroute-using-net-framework.aspx public void Traceroute(object bResolve) { bool bRes = (bool)bResolve; try { string sHostName = "",sFormat = ""; if(bRes) sFormat = "{0}\t{1} ms\t{2}\t{3}"; else sFormat = "{0}\t{1} ms\t{2}"; System.Net.IPAddress ipAddress; try { ipAddress = System.Net.Dns.GetHostEntry(RemoteIP).AddressList[0]; } catch (Exception) { ipAddress = System.Net.IPAddress.Parse(RemoteIP); //throw; } using (System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping()) { System.Net.NetworkInformation.PingOptions pingOptions = new System.Net.NetworkInformation.PingOptions(); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); byte[] bytes = new byte[32]; pingOptions.DontFragment = true; pingOptions.Ttl = 1; int maxHops = 30; fHelper.ExecuteThreadSafe(() => { fHelper.textBox1.Text = string.Format( "Tracing route to {0} over a maximum of {1} hops:", ipAddress, maxHops); fHelper.textBox1.Text += "\r\n"; }); for (int i = 1; i < maxHops + 1; i++) { stopWatch.Reset(); stopWatch.Start(); System.Net.NetworkInformation.PingReply pingReply = pingSender.Send( ipAddress, 5000, new byte[32], pingOptions); stopWatch.Stop(); if (bRes) { try { sHostName = System.Net.Dns.GetHostEntry(pingReply.Address).HostName; } catch (Exception) { sHostName = "unknown"; } } fHelper.ExecuteThreadSafe(() => { fHelper.textBox1.Text += string.Format(sFormat, i, stopWatch.ElapsedMilliseconds, pingReply.Address, sHostName); fHelper.textBox1.Text += "\r\n"; }); if (pingReply.Status == System.Net.NetworkInformation.IPStatus.Success) { fHelper.ExecuteThreadSafe(() => { fHelper.textBox1.Text += "Trace complete."; }); break; } pingOptions.Ttl++; } } } catch (Exception e) { MessageBox.Show(e.Message + ": " + RemoteIP); } }