public Ping(string[] Args, Connections Conn) { Interface.Message.Send("^6» ^7Medindo sua taxa de latência, e a taxa de latência do servidor. Aguarde...", Conn.UCID); System.Net.NetworkInformation.Ping _Ping = new System.Net.NetworkInformation.Ping(); PingReply Reply = _Ping.Send((new WebClient().DownloadString(new Uri("https://api.ipify.org/")))); PingReply ReplyMe = null; if (!string.IsNullOrWhiteSpace(Conn.IP)) { ReplyMe = _Ping.Send(Conn.IP); } else { ReplyMe = _Ping.Send("127.0.0.1"); } if (Reply.Status == IPStatus.Success && ReplyMe.Status == IPStatus.Success) { Interface.Message.Send($"^6» ^7O ping atual desse servidor é ^6{Reply.RoundtripTime.ToString()}ms", Conn.UCID); Interface.Message.Send($"^6» ^7O seu ping atual nesse servidor é ^6{ReplyMe.RoundtripTime.ToString()}ms", Conn.UCID); } else { Interface.Message.Send($"^1» ^7O seu ping ou o ping do servidor está muito alto, então não foi possível identificar.", Conn.UCID); } }
/// <summary> /// This function will deal with delays of setting up an agent. /// </summary> /// <returns>IEnumerator to allow for delays.</returns> public IEnumerator SlowAgentStart() { bool UsePublic = false; bool UseFlorida = false; //Ping Public Ip address to see if we are external.......... //GenericNetworkCore.Logger("Trying Public IP Address: " + PublicIP.ToString()); System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions po = new System.Net.NetworkInformation.PingOptions(); po.DontFragment = true; string data = "HELLLLOOOOO!"; byte[] buffer = ASCIIEncoding.ASCII.GetBytes(data); int timeout = 500; System.Net.NetworkInformation.PingReply pr = ping.Send(PublicIP, timeout, buffer, po); yield return(new WaitForSeconds(1.5f)); Debug.Log("Ping Return: " + pr.Status.ToString()); if (pr.Status == System.Net.NetworkInformation.IPStatus.Success) { GenericNetworkCore.Logger("The public IP responded with a roundtrip time of: " + pr.RoundtripTime); UsePublic = true; IP = PublicIP; } else { GenericNetworkCore.Logger("The public IP failed to respond"); UsePublic = false; } //-------------------If not public, ping Florida Poly for internal access. if (!UsePublic) { GenericNetworkCore.Logger("Trying Florida Poly Address: " + FloridaPolyIP.ToString()); pr = ping.Send(FloridaPolyIP, timeout, buffer, po); yield return(new WaitForSeconds(1.5f)); Debug.Log("Ping Return: " + pr.Status.ToString()); if (pr.Status.ToString() == "Success") { GenericNetworkCore.Logger("The Florida Poly IP responded with a roundtrip time of: " + pr.RoundtripTime); UseFlorida = true; IP = FloridaPolyIP; } else { GenericNetworkCore.Logger("The Florida Poly IP failed to respond"); UseFlorida = false; } } //Otherwise use local host, assume testing. if (!UsePublic && !UseFlorida) { IP = "127.0.0.1"; GenericNetworkCore.Logger("Using Home Address!"); } this.StartAgent(); }
private void button1_Click(object sender, EventArgs e) { label1.Visible = true; label2.Visible = true; label3.Visible = true; label1.Text = null; label2.Text = null; label3.Text = null; Ping ping = new System.Net.NetworkInformation.Ping(); try { PingReply pingreply = ping.Send(textBox1.Text); if (pingreply.Status == IPStatus.Success) { label1.ForeColor = Color.Green; label1.Text = "Success"; label2.Text = pingreply.Address.ToString(); label3.Text = pingreply.Options.Ttl.ToString(); } else { label1.ForeColor = Color.Red; label1.Text = "False"; } } catch (PingException ex) { label1.Text = "IP - не найден"; } }
public void ReadAndPing(string path) { File.OpenRead(path); ConsoleKeyInfo btn; do // Начала цикла { string ip = File.ReadLines(path); while (true) //читаем в ip строки из файла в path { //Console.WriteLine(ip); Ping pingSender = new Ping(); PingOptions options = new PingOptions(); options.Ttl = 60; //Продолжительность жизни пакета в секундах int timeout = 120; //Таймаут выводется в ответе reply.RoundtripTime string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //Строка длиной 32 байта byte[] buffer = Encoding.ASCII.GetBytes(data); //Преобразование строки в байты, выводится reply.Buffer.Length PingReply reply = pingSender.Send(ip, timeout, buffer, options); Console.WriteLine("Сервер: {0} Время={1} TTL={2}", reply.Address.ToString(), reply.RoundtripTime, reply.Options.Ttl); //Выводим всё на консоль //ConsoleKeyInfo btn = Console.ReadKey(); //Создаём переменную которая хранит метод Описывающий нажатую клавишу консоли //if (btn.Key == ConsoleKey.Escape) break; } // ConsoleKeyInfo btn = Console.ReadKey(); //Создаём переменную которая хранит метод Описывающий нажатую клавишу консоли // if (btn.Key == ConsoleKey.Escape) break; btn = Console.ReadKey(); //Переенная для чтения нажатия клавиши } while (btn.Key == ConsoleKey.Escape); //Чтение нажатия клавиши. }
/// <summary> /// Performs a pathping /// </summary> /// <param name="ipaTarget">The target</param> /// <param name="iHopcount">The maximum hopcount</param> /// <param name="iTimeout">The timeout for each ping</param> /// <returns>An array of PingReplys for the whole path</returns> public static PingReply[] PerformPathping(IPAddress ipaTarget, int iHopcount, int iTimeout) { System.Collections.ArrayList arlPingReply = new System.Collections.ArrayList(); Ping myPing = new Ping(); PingReply prResult = null; int iTimeOutCnt = 0; for (int iC1 = 1; iC1 < iHopcount && iTimeOutCnt<5; iC1++) { prResult = myPing.Send(ipaTarget, iTimeout, new byte[10], new PingOptions(iC1, false)); if (prResult.Status == IPStatus.Success) { iC1 = iHopcount; iTimeOutCnt = 0; } else if (prResult.Status == IPStatus.TtlExpired) { iTimeOutCnt = 0; } else if (prResult.Status == IPStatus.TimedOut) { iTimeOutCnt++; } arlPingReply.Add(prResult); } PingReply[] prReturnValue = new PingReply[arlPingReply.Count]; for (int iC1 = 0; iC1 < arlPingReply.Count; iC1++) { prReturnValue[iC1] = (PingReply)arlPingReply[iC1]; } return prReturnValue; }
public static bool IsHostAccessible(string hostNameOrAddress) { if (String.IsNullOrEmpty(hostNameOrAddress)) return false; using (var ping = new Ping()) { PingReply reply; try { reply = ping.Send(hostNameOrAddress, PingTimeout); } catch (Exception ex) { if (ex is ArgumentNullException || ex is ArgumentOutOfRangeException || ex is InvalidOperationException || ex is SocketException ) { return false; } throw; } if (reply != null) return reply.Status == IPStatus.Success; } return false; }
public static bool Ping(string ip) { try { if (string.IsNullOrEmpty(ip)) { return(false); } System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply reply = pingSender.Send(ip, TimeOut);//第一个参数为ip地址,第二个参数为ping的时间 if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { //ping的通 return(true); } else { //ping不通 return(false); } } catch { return(false); } }
public static bool Online(int retryTime) { Ping ping = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; PingReply reply; byte[] buffer = System.Text.Encoding.ASCII.GetBytes(string.Empty); int index = 0; while (index < retryTime) { try { reply = ping.Send("www.baidu.com", 5000, buffer, options); if (reply.Status.Equals(IPStatus.Success)) return true; } catch { } index++; } return false; }
protected override void Loop(CancellationToken token) { _isConnected = false; while (token.IsCancellationRequested == false) { bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable(); if (isNetworkAvailable) { NetworkInterface[] ifs = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface @if in ifs) { // check for wireless and up if (@if.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 && @if.OperationalStatus == OperationalStatus.Up) { var ping = new Ping(); PingReply result = ping.Send(_config.Hostname); if (result != null && result.Status == IPStatus.Success) { _isConnected = true; _connectionChanged(true); } else { // todo add timeout? _isConnected = false; _connectionChanged(false); } } } } Thread.Sleep(1000); } }
public void Execute(Arguments arguments) { var timeout = (int)arguments.Timeout.Value.TotalMilliseconds; System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); PingReply reply = null; try { reply = pingSender.Send(arguments.Hostname.Value, timeout); } catch { throw new ArgumentException("Given host is not supported or cannot be used"); } finally { Scripter.Variables.SetVariableValue(arguments.Result.Value, new BooleanStructure(false)); } bool result = reply != null && reply.Status == IPStatus.Success; if (result == false) { result = CheckConnection(arguments.Hostname.Value, 80, timeout); } if (result == false) { result = CheckConnection(arguments.Hostname.Value, 443, timeout); } Scripter.Variables.SetVariableValue(arguments.Result.Value, new BooleanStructure(result)); }
/// <summary> /// 检测IP /// </summary> /// <param name>strIP</param> /// <returns></returns> public static bool PingIP(string strIP, ref long pingReplyRoundtripTime) { try { if (!IsValidIP(strIP)) { return(false); } System.Net.NetworkInformation.Ping psender = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply prep = psender.Send(strIP, 500, Encoding.Default.GetBytes("welcome_use_this_soft_write_by_airotop")); if (prep.Status == System.Net.NetworkInformation.IPStatus.Success) { pingReplyRoundtripTime = prep.RoundtripTime; return(true); } return(false); } catch (Exception ex) { // MessageBox.Show(ex.Message); string date_str = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString(); ClassLog.Writelog(date_str, " ServrerMonitor_PingIP ", ex.Message); return(false); } }
private bool check_connection() { using (System.Net.NetworkInformation.Ping png = new System.Net.NetworkInformation.Ping()) { System.Net.IPAddress addr; System.Net.IPAddress localhostaddr; addr = new System.Net.IPAddress(AddrBytes); localhostaddr = new System.Net.IPAddress(LocalhostBytes); try { if (checkBox1.Checked ? (png.Send(localhostaddr, 1500, new byte[] { 0, 1, 2, 3 }).Status == IPStatus.Success) : (png.Send(addr, 1500, new byte[] { 0, 1, 2, 3 }).Status == IPStatus.Success)) { return(true); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(false); } } return(false); }
///最近项目中需要实现 类 cmd 命令ping 的操作。查看当前Ip是否畅通。 public static bool Ping(string ip) { try { Ping p = new System.Net.NetworkInformation.Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; string data = "Test Data!"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 1000; PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == IPStatus.Success) { return(true); } else { return(false); } } catch (Exception) { return(false); } }
public bool isTargetWebsiteUp(Uri targetWebsite) { string[] sector = targetWebsite.Segments; string strURL = targetWebsite.ToString(); char[] delimeterChars = sector[0].ToCharArray(); sector = strURL.Split(delimeterChars); for (int i = 0; i < sector.Length; i++) { Console.WriteLine(String.Format("Sector{0}: " + sector[i], i)); } lastSector = sector[sector.Length]; fileExtentsion = lastSector.Split('.')[lastSector.Split('.').Length]; Ping ping = new System.Net.NetworkInformation.Ping(); var result = ping.Send(sector[2]); if (result.Status != System.Net.NetworkInformation.IPStatus.Success) { errorCode = -1; Console.WriteLine(result.Address + " failed to relpy"); return(false); } else { Console.WriteLine(result.Address + " replied in " + result.RoundtripTime + "ms" + Environment.NewLine + "Reason: " + result.Status); return(true); } }
} // Main() public static long ping(string pingTarget, int timeout) { // Ping's the local machine. System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply reply; try { reply = pingSender.Send(pingTarget, timeout); } catch (Exception e) { Console.Error.WriteLine(e.ToString().Split('\n')[0]); // e.Message return(-1); } if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { println( DateTime.Now.ToString("HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture) // "yyyy-MM-dd" + " Reply from " + reply.Address.ToString() + ": bytes=" + reply.Buffer.Length + " time=" + reply.RoundtripTime + "ms TTL=" + reply.Options.Ttl ); //Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment); return(reply.RoundtripTime); } else { println(DateTime.Now.ToString("HH:mm:ss.fff ", System.Globalization.CultureInfo.InvariantCulture) + reply.Status.ToString()); return(-1); } } // ping()
/// <summary> /// Ping network address /// </summary> /// <param name="address">IP Address or Hostname</param> /// <returns></returns> public static bool SendPing(string address, int tries) { int tries_count = 0; Ping pingSender = new Ping (); PingOptions options = new PingOptions (); // Use the default Ttl value which is 128, // but change the fragmentation behavior. options.DontFragment = true; // Create a buffer of 32 bytes of data to be transmitted. string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes (data); int timeout = 120; while (tries_count < tries) { PingReply reply = pingSender.Send(address, timeout, buffer, options); if (reply.Status == IPStatus.Success) return true; tries_count++; } return false; }
/// <summary> /// ping using host name or ip address /// </summary> /// <param name="HostnameorAddress">example :- www.google.com or 192.168.1.2</param> /// <returns> /// <c>error message</c>if ip address or host name is invalid or network connection is unavailable: otherwise, <c>success</c>. /// </returns> public static string PingHost(string HostnameorAddress) { try { if (HostnameorAddress != string.Empty) { var ping = new System.Net.NetworkInformation.Ping(); var result = ping.Send(HostnameorAddress); string[] pin = new string[6]; if (result.Status == System.Net.NetworkInformation.IPStatus.Success) { return result.Status.ToString() + "\n" + result.Address.MapToIPv4(); } else { return result.Status.ToString(); } } return "ip address cannot be null"; } catch (NetworkInformationException e) { return e.Message; } catch (Exception e) { return e.Message; } }
public bool Ping(string host, int attempts, int timeout) { bool rsp = false; try { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingReply; for (int atmpt = 0; atmpt < attempts; atmpt++) { try { pingReply = ping.Send(host, timeout); if (pingReply != null && pingReply.Status == System.Net.NetworkInformation.IPStatus.Success) { rsp = true; } } catch { rsp = false; } } } catch (Exception e) { MessageBox.Show(e.Message); } return(rsp); }
public static PingStatus Ping(string deviceName, PingerOptions options) { Ping pinger = new Ping(); PingOptions pingOptions = new PingOptions() { DontFragment = options.DontFragment }; // Create a buffer of 32 bytes of data to be transmitted. byte a = Encoding.ASCII.GetBytes("a")[0]; byte[] buffer = new byte[options.PayloadSize]; // Encoding.ASCII.GetBytes(data); for (int i = 0; i < options.PayloadSize; i++) { buffer[i] = a; } try { PingReply reply = pinger.Send(deviceName, options.Timeout, buffer, pingOptions); if (reply.Status == IPStatus.Success) { //Ping was successful return new PingStatus(true, (int)reply.Status, reply.RoundtripTime); } //Ping failed return new PingStatus(false, (int)reply.Status, reply.RoundtripTime); } catch (Exception) { return new PingStatus(false, 99999, 99999); } }
private static ConcurrentBag <PingResult> GetPingResults(IEnumerable <InternetUser> internetUsers, int timeout) { var results = new ConcurrentBag <PingResult>(); Parallel.ForEach(internetUsers, (internetUser) => { System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); try { PingReply reply = pingSender.Send(internetUser.IpAddress, timeout); results.Add(new PingResult { InternetUserId = internetUser.Id, IpAddress = internetUser.IpAddress, Recorded = DateTime.UtcNow, Status = reply.Status.ToString(), Time = reply.RoundtripTime }); } catch (Exception) { results.Add(new PingResult { InternetUserId = internetUser.Id, IpAddress = internetUser.IpAddress, Status = "Failed", Recorded = DateTime.UtcNow, Time = 0 }); } }); return(results); }
static void Main(string[] args) { // Set up a new variable that pings. var ping = new Ping(); // Asks the user what website they want to ping. Console.WriteLine("What website do you want to check? Example(www.google.co.uk)"); // Records their input. var website = Console.ReadLine(); // Records the result of the ping. var result = ping.Send(website); // Set up an if else statement for if it fails or not. if (result.Status != IPStatus.Success) { // If fails website is down. Console.WriteLine("Website is Down."); } else { // If anything else i.e suceeds prints it is up. Console.WriteLine("Website is Up."); } // Stops program from terminating. Console.ReadLine(); }
private void GetPingResult_new(object son) { Person person = son as Person; int i = person.Id; string url = person.Url; try { System.Net.NetworkInformation.Ping p1 = new System.Net.NetworkInformation.Ping(); //只是演示,没有做错误处理 PingReply reply = p1.Send(url); //阻塞方式 if (reply.Status == IPStatus.Success) { dt1.Rows[i][2] = reply.Address.ToString(); dt1.Rows[i][3] = "OK"; dt1.Rows[i][4] = reply.RoundtripTime; y++; OutDelegateNew outdelegate = new OutDelegateNew(OutTextNew); this.Dispatcher.BeginInvoke(outdelegate, new object[] { url, "模式ping" }); } else { forbid_url.Add(url); } } catch { forbid_url.Add(url); } }
public static bool PingTest(string aIPAddr) { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply reply = p.Send(aIPAddr); return(reply.Status.Equals(IPStatus.Success) ? true : false); }
/// <summary> /// Метод выполнения пинга /// </summary> /// <returns></returns> private bool PingOperation() { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); PingReply reply = null; try { reply = ping.Send(this.IPAddress); if (reply.Status != IPStatus.TimedOut) { this.Latency = reply.RoundtripTime.ToString(); } else { this.Latency = "-"; } if (this.Latency == "0") { this.Latency = "-"; } } catch { this.Latency = "-"; } return(this.Latency != "-"); }
public RemoteEnvironment(string ipAddress, string userName, string password, string psExecPath) { IpAddress = ipAddress; UserName = userName; Password = password; _psExecPath = psExecPath; // wait for ping RetryUtility.RetryAction(() => { var ping = new Ping(); var reply = ping.Send(IpAddress); OsTestLogger.WriteLine(string.Format("Pinging ip:{0}, reply: {1}", ipAddress, reply.Status)); if (reply.Status != IPStatus.Success) throw new InvalidOperationException(string.Format("Remote IP {0} ping returns {1}", ipAddress, reply.Status)); }, 50, 5000); // give time for the RPC service to start RetryUtility.RetryAction(() => { WmiWrapperInstance = new WmiWrapper(ipAddress, userName, password); }, 10, 5000); WindowsShellInstance = new WindowsShell(this, psExecPath); //this will populate the GuestEnvironmentVariables. Short time after start APPDATA may be empty RetryUtility.RetryAction( InvalidateCachedGuestEnvironmentVariables, 10, 10000); IsUACEnabled = CheckIsUAC(); }
public static bool CheckServerConnectivity(string ipAddress) { bool connectionExists = false; string status = ""; try { System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; if (!string.IsNullOrEmpty(ipAddress)) { System.Net.NetworkInformation.PingReply reply = pingSender.Send(ipAddress); connectionExists = reply.Status == System.Net.NetworkInformation.IPStatus.Success ? true : false; } } catch (PingException ex) { status = ex.Message.ToString(); } catch (AggregateException ex) { foreach (Exception inner in ex.InnerExceptions) { status = inner.Message.ToString(); } } return(connectionExists); }
/// <summary> /// Gets latency data. /// </summary> private void Ping() { // start pinging PingReply pingReply = _p.Send(_url); // get ping long ping = pingReply.RoundtripTime; // calculate time passed TimeSpan timeDifference = DateTime.UtcNow - _startTime; // create pinger data PingerData pingerData = null; switch (pingReply.Status) { case IPStatus.Success: pingerData = PingerData.CreateSuccess(ping, timeDifference); break; case IPStatus.TimedOut: default: pingerData = PingerData.CreateTimeout(timeDifference); break; } // notify OnNewPing(pingerData); }
public List <string> PingLan(string ip) { System.Net.NetworkInformation.Ping pngs = new System.Net.NetworkInformation.Ping(); List <string> addresses = new List <string>(); for (int i = 0; i < 255; i++) { string listhost = ip + i; try { var status = pngs.Send(listhost, 1).Status; if (status == System.Net.NetworkInformation.IPStatus.Success) { string curr = "Host " + listhost + " available"; addresses.Add(curr); } } catch (InvalidOperationException e) { } } return(addresses); }
private void PingService() { try { using (var ping = new System.Net.NetworkInformation.Ping()) { _lastPingTime = DateTime.Now; var reply = ping.Send(_host, _timeout); if (reply.Status != IPStatus.Success) { _lastPingResult = HealthCheckResult.Unhealthy(); } else if (reply.RoundtripTime >= _timeout) { _lastPingResult = HealthCheckResult.Degraded(); } else { _lastPingResult = HealthCheckResult.Healthy(); } } } catch { _lastPingResult = HealthCheckResult.Unhealthy(); } }
/// <summary> /// ping 具体的网址看能否ping通 /// </summary> /// <param name="strNetAdd"></param> /// <returns></returns> private static bool PingNetAddress(string strNetAdd) { bool Flage = false; System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.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; } return(Flage); }
/* Ping an entered address */ public void PingAddress(string addr) { List<IPStatus> replies = new List<IPStatus>(); int count = 0; // send 4 pings while (count < 4) { // used to construct a 32 byte message string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 120; // intalize the ping object with ttl and no fragment options PingOptions PingSettings = new PingOptions(53, true); Ping Pinger = new Ping(); // send the ping PingReply Reply = Pinger.Send(addr, timeout, buffer, PingSettings); replies.Add(Reply.Status); ++count; } // tracks the ammount of successful replies for (int i = 0; i < replies.Count; i++) if (replies[i] == IPStatus.Success) scount++; }
// 按钮点击事件 private void button1_Click(object sender, EventArgs e) { //这里是首先将Ping类进行引入 var PingPro = new System.Net.NetworkInformation.Ping(); //将包发去目标地址进行判断 var result = PingPro.Send(ipName); //判断是否成功 if (result.Status != System.Net.NetworkInformation.IPStatus.Success) { return; } // 输出调试(result返回类型,只需要将其渲染到richText就可以了 Console.WriteLine("这里是返回包的内容:" + result.Address + " " + result.RoundtripTime); globalPing = result; //数据渲染 richTextBox1.AppendText("**************************************\n"); richTextBox1.AppendText("答复的主机地址:" + result.Address + "\n"); richTextBox1.AppendText("往返时间:" + result.RoundtripTime + "\n"); richTextBox1.AppendText("缓冲区大小:" + result.Buffer.Length + "\n"); richTextBox1.AppendText("生存时间(TTL):" + result.Options.Ttl + "\n"); richTextBox1.AppendText("是否分段:" + result.Options.DontFragment + "\n"); richTextBox1.AppendText("**************************************\n"); }
public override bool DoValidate() { #if !NET_CORE Ping p = new Ping();//创建Ping对象p PingReply pr = p.Send("www.baidu.com", 30000);//向指定IP或者主机名的计算机发送ICMP协议的ping数据包 if (pr != null && pr.Status == IPStatus.Success)//如果ping成功 { return true; } #else HttpClient clinet = new HttpClient(); IAsyncResult asyncResult = clinet.GetStringAsync("http://www.baidu.com"); if (!asyncResult.AsyncWaitHandle.WaitOne(2000)) { return false; } if (((Task<string>)asyncResult).Result.Contains("<title>百度一下,你就知道</title>")) { return true; } Thread.Sleep(100); #endif return false; }
public bool PingHost(string Address, int TimeOut = 1000) { try { using (System.Net.NetworkInformation.Ping PingSender = new System.Net.NetworkInformation.Ping()) { PingOptions Options = new PingOptions(); Options.DontFragment = true; string Data = "test"; byte[] DataBuffer = Encoding.ASCII.GetBytes(Data); PingReply Reply = PingSender.Send(Address, TimeOut, DataBuffer, Options); if (Reply.Status == IPStatus.Success) { return(true); } return(false); } } catch (Exception) { lbError.Visible = true; lbError.Text = "网络连接异常,请检查!!!"; //MessageBox.Show("网络连接异常"); return(false); } }
/// <summary> /// ping using ip address /// </summary> /// <param name="IPaddress">example :- 192.168.1.1</param> /// <returns> /// <c>error message</c>if ip address or host name is invalid or network connection is unavailable: otherwise, <c>success</c>. /// </returns> public static string PingHost(IPAddress IPaddress) { try { var ping = new System.Net.NetworkInformation.Ping(); var result = ping.Send(IPaddress); string[] pin = new string[6]; if (result.Status == System.Net.NetworkInformation.IPStatus.Success) { return result.Status.ToString() + "\n" + result.Address.MapToIPv4(); } else { return result.Status.ToString(); } } catch (NetworkInformationException e) { return e.Message; } catch (Exception e) { return e.Message; } }
public void ParseHTML() { Ping q = new Ping(); try { PingReply an = q.Send("ares.elcom.local"); if (an.Status == IPStatus.Success) { for (Int16 i = 0; i < tIDVal.Count; i++) { idTemp = tIDVal[i]; address = "http://ares/Divisions/Lists/Employees/DispForm.aspx?ID=" + idTemp + "&Source=http%3A%2F%2Fares%2FDivisions%2FLists%2FEmployees%2FPhoneList%2Easpx"; GetPic(); } dbc.EployeeBirthDayWrite(tBirthDay, tStartDay, tBirthID); } } catch { } }
private void pingBaidu() { try { Ping p = new Ping(); PingReply pr = p.Send("www.baidu.com"); if (pr.Status == IPStatus.Success||true) { MainWindow mw = new MainWindow(); mw.Show(); this.Close(); } else { MessageBox.Show("本程序需要网络连接,请先配置好当前网络环境"); return; } } catch (Exception) { MessageBox.Show("本程序需要网络连接,请先配置好当前网络环境"); return; } }
/// <summary> /// Ping命令检测网络是否畅通 /// </summary> /// <param name="urls">URL数据</param> /// <param name="errorCount">ping时连接失败个数</param> /// <returns></returns> public static string MyPing(string[] urls, out int errorCount) { StringBuilder sb = new StringBuilder(); Ping ping = new Ping(); errorCount = 0; try { PingReply pr; for (int i = 0; i < urls.Length; i++) { pr = ping.Send(urls[i]); if (pr.Status != IPStatus.Success) { sb.AppendLine("error Ping " + urls[i] + " " + pr.Status.ToString()); errorCount++; } sb.AppendLine("Ping " + urls[i] + " " + pr.Status.ToString()); } } catch (Exception ex) { sb.AppendLine("error!! " + ex.Message); errorCount = urls.Length; } //if (errorCount > 0 && errorCount < 3) // isconn = true; return sb.ToString(); }
private void EmitFreshData() { if (EmitData != null) { try { var ping = new System.Net.NetworkInformation.Ping(); var pingResult = ping.Send(_URL); var outString = ""; if (pingResult == null) { outString = "Unknown Ping Error"; FarsightLogger.DefaultLogger.LogWarning(outString); } else { if (pingResult.Status == IPStatus.Success) { outString = $"Reply from {pingResult.Address}: time={pingResult.RoundtripTime}ms"; } else { outString = $"Error: {pingResult.Status}"; } } EmitData(this, new EmitDataHandlerArgs(outString)); } catch (Exception ex) { EmitData(this, new EmitDataHandlerArgs("ERROR: " + ex.Message)); } } }
public PingReply Ping(string hostOrIp) { Ping pingSender = new Ping(); //Ping 选项设置 PingOptions options = new PingOptions(); options.DontFragment = true; //测试数据 string data = "test data abcabc"; byte[] buffer = Encoding.ASCII.GetBytes(data); //设置超时时间 int timeout = 1200; //调用同步 send 方法发送数据,将返回结果保存至PingReply实例 var reply = pingSender.Send(hostOrIp, timeout, buffer, options); if (reply.Status == IPStatus.Success) { return reply; /*lst_PingResult.Items.Add("答复的主机地址:" + reply.Address.ToString()); lst_PingResult.Items.Add("往返时间:" + reply.RoundtripTime); lst_PingResult.Items.Add("生存时间(TTL):" + reply.Options.Ttl); lst_PingResult.Items.Add("是否控制数据包的分段:" + reply.Options.DontFragment); lst_PingResult.Items.Add("缓冲区大小:" + reply.Buffer.Length); */ } else throw new ApplicationException("Can't find the arrive at target " + hostOrIp.ToString()); }
public bool StartConnect(string IP, int TcpPort, int CtrlPort) { var ping = new Ping(); if (ping.Send(IP).Status != IPStatus.Success) { Console.Write("サーバーがPINGに応答しません。接続しますか?\n10秒でキャンセルされます。(y/n):"); string Res = new Reader().ReadLine(10000); if (Res == null || !Res.ToLower().StartsWith("y")) return false; } CommonManager.Instance.NWMode = true; if (!CommonManager.Instance.NW.ConnectServer(IP, (uint)CtrlPort , (uint)TcpPort, OutsideCmdCallback, this)) return false; byte[] binData; if (CommonManager.Instance.CtrlCmd.SendFileCopy("ChSet5.txt", out binData) == 1) { string filePath = @".\Setting"; Directory.CreateDirectory(filePath); filePath += @"\ChSet5.txt"; using (BinaryWriter w = new BinaryWriter(File.Create(filePath))) { w.Write(binData); w.Close(); } ChSet5.LoadFile(); return true; } return false; }
public static void Connect() { try { var ping = new Ping(); var reply = ping.Send(IpAdress, 10); Logger.Info("Attempting to connect to server."); if (reply.Status == IPStatus.Success) { MainTcpClient = new TcpClient(IPAddress.Parse(IpAdress).ToString(), Port); Logger.Info($"{((IPEndPoint)MainTcpClient.Client.RemoteEndPoint).Address}" + ": Connected to server."); MainStream = MainTcpClient.GetStream(); } else { Logger.Info("Failed to connect to server."); throw new PingException("Servern är inte aktiv"); } } catch (PingException pingException) { Console.WriteLine("PingException: " + pingException.Message); } catch (SocketException socketException) { Console.WriteLine("SocketException:" + socketException.Message); } }
public void Execute(Arguments arguments) { System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); long sum = 0; for (int i = 0; i < arguments.Repeats.Value; i++) { PingReply reply = pingSender.Send(arguments.Ip.Value, (int)arguments.Timeout.Value.TotalMilliseconds); if (reply.Status == IPStatus.Success) { sum += reply.RoundtripTime; } else if (reply.Status == IPStatus.TimedOut) { throw new PingException("Destination host do not respond to ping"); } else if (reply.Status == IPStatus.TimeExceeded) { throw new PingException("Destination host connection has timed out"); } else { throw new PingException("Destination host unreachable"); } } var roundedReplyTime = sum / arguments.Repeats.Value; Scripter.Variables.SetVariableValue(arguments.Result.Value, new IntegerStructure((int)roundedReplyTime)); }
public void PingHost(Host host, int numeroTestes) { bool pingou = true; Ping pinger = new Ping(); try { for (int i = 0; i < numeroTestes; i++) { if (!pingou) break; PingReply reply = pinger.Send(host.ip); pingou = reply.Status == IPStatus.Success; } } catch (PingException) { pingou = false; } if (host.em_pe != pingou) { host.em_pe = pingou; host.ultima_alteracao = DateTime.Now.ToString(); banco.atualizarHost(host); } }
public void pingHost(string hostName, int pingCount) { if (pingCount == 0) { pingCount = 43200; } Console.WriteLine("Host, Response Time, Status, Time "); String fileName = String.Format(@"tping-{0}-{1}-{2}-{3}.csv", DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); for (int i = 0; i < pingCount; i++) { Ping ping = new Ping(); StreamWriter processedData = new StreamWriter(@fileName, true); try { PingReply pingReply = ping.Send(hostName); processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status); processedData.Close(); Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status); } catch (System.Net.NetworkInformation.PingException) { processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error"); Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error"); processedData.Close(); //Console.WriteLine(Ex); //Environment.Exit(0); } Thread.Sleep(2000); } Console.WriteLine("\n" + "tping complete - {0} pings logged in {1}", pingCount, fileName); }
private bool Ping() { Ping pingSender = new Ping(); if (string.IsNullOrEmpty(_hostAddress)) { try { IPInfo ipInfo = IPInfo.CreateFromMac(_macAddress); _hostAddress = ipInfo.IPAddress; } catch (Exception ex) { _logger.Warn(ex.Message); return false; } } PingReply reply = pingSender.Send(_hostAddress); IPStatus status = reply.Status; if (reply.Status == IPStatus.Success) { return true; } return false; }
public string TargetFound(string target) { try { Ping pingSender = new Ping(); PingOptions options = new PingOptions(); // Use the default Ttl value which is 128, // but change the fragmentation behavior. options.DontFragment = true; // Create a buffer of 32 bytes of data to be transmitted. string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 120; PingReply reply = pingSender.Send(target, timeout, buffer, options); if (reply.Status == IPStatus.Success) { return "targetfound"; } else { return "targetnotfound"; } } catch(Exception e) { string CaughtException = e.ToString(); return CaughtException.Substring(0, CaughtException.IndexOf(Environment.NewLine)); } }
public bool IsNetWork() { string url = "www.baidu.com"; System.Net.NetworkInformation.Ping ping; System.Net.NetworkInformation.PingReply res; ping = new System.Net.NetworkInformation.Ping(); try { res = ping.Send("www.baidu.com"); if (res.Status == IPStatus.Success) { return(true); } else { return(false); } } catch (Exception) { return(false); } }
public bool CanPing(string address) { Ping ping = new Ping(); try { PingReply reply = ping.Send(address); if (reply == null) return false; if (reply.Status == IPStatus.Success) { this.Log.Debug("On-Line!"); return true; } else { this.Log.Debug("Off-Line"); return false; } } catch (PingException) { this.Log.Debug("Off-Line"); return false; } }
/// <summary> /// Checks available version. /// </summary> public static string CheckForNewVersion() { try { Ping ping = new Ping(); PingReply reply = ping.Send(PING_TEST_WEB_SITE); if (reply.Status == IPStatus.Success) { string httpQuery = PING_WEBSERVICE + "?v=" + TechnicalSettings.SoftwareVersion; WebRequest web = System.Net.HttpWebRequest.Create(httpQuery); WebResponse response = web.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); string xml = sr.ReadToEnd(); response.Close(); if (xml.Contains(VERSION)) { int a = xml.IndexOf(VERSION); int b = xml.IndexOf("</version>"); string version = xml.Substring(a + VERSION.Length, b - a - VERSION.Length); if (TechnicalSettings.IsThisVersionNewer(version)) { return version; } } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("AppMain.PingWeb failed. \n" + ex.Message); } return null; }
/// <summary> /// Will use CheckOrResolveIpAddress() to get an IP Address, then try to ping it. /// </summary> /// <param name="toPing">The IP Address or Hostname to ping</param> /// <returns>Null if successful. The error message if an error occurred.</returns> private static string Ping(string toPing) { IPAddress ipAddress = CheckOrResolveIpAddress(toPing); if (ipAddress == null) return "Invalid IP Address/Hostname"; Ping ping = new Ping(); PingReply reply; try { reply = ping.Send(ipAddress); } catch (PingException pe) { return string.Format("Could not ping {0}, {1}", toPing, pe.Message); } catch (Exception e) { return string.Format("Could not ping {0}, {1}", toPing, e.Message); } if (reply != null && reply.Status == IPStatus.Success) { //string message = reply.Status.ToString(); return null; } return string.Format("Could not ping {0}", toPing); }
bool ConnectGoogleTW() { //Google網址 string googleTW = "www.google.tw"; //Ping網站 Ping p = new Ping(); //網站的回覆 PingReply reply; try { //取得網站的回覆 reply = p.Send(googleTW); //如果回覆的狀態為Success則return true if (reply.Status == IPStatus.Success) { return true; } } //catch這裡的Exception, 是有可能網站當下的某某狀況造成, 可以直接讓它傳回false. //或在重覆try{}裡的動作一次 catch { return false; } //如果reply.Status !=IPStatus.Success, 直接回傳false return false; }
private void Ping() { const int BufferSize = 32; const int TimeToLive = 128; byte[] buffer = new byte[BufferSize]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = unchecked ((byte)i); } using (System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping()) { PingOptions options = new PingOptions(TimeToLive, false); for (int i = 0; i < this.PingCount; i++) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Pinging {0}", this.HostName)); PingReply response = pinger.Send(this.HostName, this.Timeout, buffer, options); if (response != null && response.Status == IPStatus.Success) { this.Exists = true; return; } if (response != null) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Response Status {0}", response.Status)); } System.Threading.Thread.Sleep(1000); } this.Exists = false; } }
public static bool PingIpOrDomainName(string strIpOrDname) { try { Ping objPingSender = new Ping(); PingOptions objPinOptions = new PingOptions(); objPinOptions.DontFragment = true; string data = ""; byte[] buffer = Encoding.UTF8.GetBytes(data); int intTimeout = 120; PingReply objRPinReply = objPingSender.Send(strIpOrDname, intTimeout, buffer, objPinOptions); string strInfo = objRPinReply.Status.ToString(); if (strInfo == "Success") { return true; } else { return false; } } catch (Exception) { return false; } }
// 检查网络连接的函数 public void checkNet() { Ping p = new Ping();//创建Ping对象p PingReply pr = p.Send(_Sip);//向指定IP或者主机名的计算机发送ICMP协议的ping数据包 if (pr.Status == IPStatus.Success)//如果ping成功 { Console.WriteLine("网络连接成功, 执行下面任务..."); netIsOk = true; } else { int times = 0;//重新连接次数; do { if (times >= 1) { MessageBox.Show("重新尝试连接超过12次,连接失败程序结束"); netIsOk = false; return; } // Thread.Sleep(5000);//等待十分钟(方便测试的话,你可以改为1000) pr = p.Send(_Sip); Console.WriteLine(pr.Status); times++; } while (pr.Status != IPStatus.Success); MessageBox.Show("连接成功"); netIsOk = true; times = 0;//连接成功,重新连接次数清为0; } }
private String pingIps(String firstBit, String myAddr) { String curIp; for (int i = 1; i <= 255; i++) { output.text = i + ""; Debug.Log("Go " + DateTime.Now.ToString("HH:mm:ss tt")); curIp = firstBit + "." + i; try { System.Net.NetworkInformation.PingReply rep = p.Send(curIp, 100); output.text = "pinged " + i; if (rep.Status == System.Net.NetworkInformation.IPStatus.Success && curIp != myAddr) { return(curIp); //host is active } } catch (Exception e) { output.text = e + ""; } } return(""); }
private void PingServer(string server) { string result = "Test failed!"; var pingSender = new Ping(); var options = new PingOptions(); options.DontFragment = true; // Create a buffer of 32 bytes of data to be transmitted. const string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); const int timeout = 120; try { var reply = pingSender.Send(server, timeout, buffer, options); if (reply != null && reply.Status == IPStatus.Success) { result = String.Format("Address: {0}\n", reply.Address.ToString()); result += String.Format("RoundTrip time: {0}\n", reply.RoundtripTime); result += String.Format("Buffer size: {0}\n", reply.Buffer.Length); result += Environment.NewLine; result += "Test successful!\n"; } } catch (Exception) { } MessageBox.Show(result, "Test Result"); }
public static PingResult PingHost(string host, int timeout = 1000, int pingCount = 4, int waitTime = 100) { PingResult pingResult = new PingResult(); IPAddress address = GetIpFromHost(host); byte[] buffer = new byte[32]; PingOptions pingOptions = new PingOptions(128, true); using (Ping ping = new Ping()) { for (int i = 0; i < pingCount; i++) { try { PingReply pingReply = ping.Send(address, timeout, buffer, pingOptions); if (pingReply != null) { pingResult.PingReplyList.Add(pingReply); } } catch (Exception e) { DebugHelper.WriteException(e); } if (waitTime > 0 && i + 1 < pingCount) { Thread.Sleep(waitTime); } } } return pingResult; }
/// <summary> /// Проверка доступности сервера /// </summary> /// <param name="Server">Адрес сервера</param> /// <returns></returns> public static Boolean IsOKServer(string Server, int timeout = 800) { /*WebRequest request = WebRequest.Create(Server); * String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(login + ":" + password)); * request.Headers.Add("Authorization", "Basic " + encoded); * request.Timeout = timeout; * try * { * HttpWebResponse response = (HttpWebResponse)request.GetResponse(); * if (response == null || (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.BadRequest)) * { * return false; * } * response.Close(); * } * catch * { * return false; * } * return true;*/ try { Server = Server.Replace("http://", "").Replace("/", "").Split(':').First(); var ip = IPAddress.Parse(Server); var p = new System.Net.NetworkInformation.Ping(); var rq = p.Send(ip, timeout, new byte[] { 100, 200 }); return(rq.Status == System.Net.NetworkInformation.IPStatus.Success); } catch { //Console.WriteLine("PING Error"); return(false); } }
public static string SendPing(string host, int count) { string[] status = new string[count]; using (Ping ping = new Ping()) { PingReply reply; //byte[] buffer = Encoding.ASCII.GetBytes(new string('a', 32)); for (int i = 0; i < count; i++) { reply = ping.Send(host, 3000); if (reply.Status == IPStatus.Success) { status[i] = reply.RoundtripTime.ToString() + " ms"; } else { status[i] = "Timeout"; } Thread.Sleep(100); } } return string.Join(", ", status); }