} // ///////////////////////////////////////////////////////////////////// void TaskFunc(AdressIndex indata) { Ping png = new Ping(); bool first = true; IPStatus prevStatus = IPStatus.Unknown; PingTimeSaver pingTimeSaver = new PingTimeSaver(indata.adress); while (true) { long start = DateTime.Now.Ticks; PingReply reply = png.Send(indata.adress, indata.timeout); Brush brush = GetBrush(reply); setBrush(brush, indata.index); if (first || (prevStatus == IPStatus.Success ^ reply.Status == IPStatus.Success)) { first = false; SaveReplay(indata.adress, reply); prevStatus = reply.Status; } if (reply.Status == IPStatus.Success) { pingTimeSaver.Add(reply.RoundtripTime, reply.Status); } int timeInWork = (int)((DateTime.Now.Ticks - start) / 10000); if (timeInWork < indata.timecycle) { Thread.Sleep(indata.timecycle - timeInWork); } } } // ////////////////////////////////////////////////////////////////////////
/// <summary> Create the object </summary> public PingStatus(IPStatus StatusCode, String Destination, long RoundTripTime) { this.StatusCode = StatusCode; this.Destination = Destination; this.ResponseTime = RoundTripTime; ConfigureProperties(); }
/////////////////////////////////////////////////////////////////////////////////////////////// #region Public Diagnostic Methods public static ReturnCode Ping( string hostNameOrAddress, int timeout, ref IPStatus status, ref long roundtripTime, ref Result error ) { try { using (Ping ping = new Ping()) { PingReply reply = ping.Send(hostNameOrAddress, timeout); // // NOTE: Populate reply information for the caller. // status = reply.Status; roundtripTime = reply.RoundtripTime; } return(ReturnCode.Ok); } catch (Exception e) { // // NOTE: Populate error information for the caller. // error = e; } return(ReturnCode.Error); }
public PingInfo(IPAddress ipAddress, int bytes, long time, IPStatus status) { IPAddress = ipAddress; Bytes = bytes; Time = time; Status = status; }
public void run() { String file = "uptime.csv"; File.AppendAllText(file, String.Format("{0},START,\n", getTime())); while (!Stop) { PingReply reply = pingSender.Send(address); if (reply.Status != lastStat) { String log = ""; if (reply.Status == IPStatus.Success) { log = String.Format("{0},UP,\n", getTime()); } else if (reply.Status == IPStatus.TimedOut) { log = String.Format("{0},DOWN,\n", getTime()); } else { log = String.Format("{0},ONBEKENT,\"{1}\"\n", getTime(), reply.Status); } lastStat = reply.Status; File.AppendAllText(file, log); } Thread.Sleep(1000); } File.AppendAllText(file, String.Format("{0},STOP,\n", getTime())); }
/// <summary> /// </summary> /// <param name="ip"></param> /// <param name="hostName"></param> /// <param name="roundTripTime">in ms</param> /// <param name="status">The status of sending an Internet Control Message Protocol (ICMP) echo message to a computer.</param> public HopEventArgs(string ip, string hostName, long roundTripTime, IPStatus status) { IP = ip; HostName = hostName; RoundTripTime = roundTripTime; Status = status; }
public void WriteResult(IPStatus status, string address) { using (StreamWriter output = new StreamWriter("output.txt")) { output.WriteLine($"{status} | {address} | {DateTime.Now}"); } }
private void ProcessHop(IPAddress ip, IPStatus status) { long roundTripTime = 0; if (status == IPStatus.TtlExpired || status == IPStatus.Success) { var pingIntermediate = new Ping(); try { //Compute roundtrip time to the address by pinging it PingReply reply = pingIntermediate.Send(ip, Timeout); roundTripTime = reply.RoundtripTime; status = reply.Status; } catch (PingException e) { //Do nothing System.Diagnostics.Trace.WriteLine(e); } pingIntermediate.Dispose(); } ++Hops; if (ip == null) { IsDone = true; } else { FireHop(ip, roundTripTime, status); IsDone = ip.Equals(IP) || Hops == MaxHops; } if (IsDone) { FireDone(); } }
private void ProcessHop(IPAddress address, IPStatus status) { var roundTripTime = this.GetRoundtripTime(address, ref status); if (this.cancel) { return; } var hop = new TraceRouteHopData(this.counter++, address, roundTripTime, status, this.ResolveNames); lock (this.hopList) { this.hopList.Add(hop); } this.OnRouteHopFound(hop); this.Idle = address.Equals(this.destinationIP); lock (this.hopList) { if (!this.Idle && this.hopList.Count >= this.HopLimit - 1) { this.ProcessHop(this.destinationIP, IPStatus.Success); } } if (this.Idle) { this.OnCompleted(); this.Dispose(); } }
private static PingReply CreatePingReplyFromIcmpEchoReply(Interop.IpHlpApi.IcmpEchoReply reply) { const int DontFragmentFlag = 2; IPAddress address = new IPAddress(reply.address); IPStatus ipStatus = (IPStatus)reply.status; // The icmpsendecho IP status codes. long rtt; PingOptions options; byte[] buffer; rtt = reply.roundTripTime; if (ipStatus == IPStatus.Success) { // Only copy the data if we succeed w/ the ping operation. options = new PingOptions(reply.options.ttl, (reply.options.flags & DontFragmentFlag) > 0); buffer = new byte[reply.dataSize]; Marshal.Copy(reply.data, buffer, 0, reply.dataSize); } else { options = default(PingOptions); buffer = Array.Empty <byte>(); } return(new PingReply(address, options, ipStatus, rtt, buffer)); }
public void SetICMPStatus(IPStatus replyStatus) { lock (this) { // ogólne statystyki this.totalPings++; if (replyStatus == IPStatus.Success) { this.responsesInARow++; this.failsInARow = 0; } else { this.responsesInARow = 0; this.failsInARow++; } // status odpowiedzi (ostatniej) this.icmpStatus = replyStatus; if (replyStatus == IPStatus.Success) { this.currentReplyStatus = PingReplyStatus.Success; } if (replyStatus == IPStatus.TimedOut || replyStatus == IPStatus.TimeExceeded) { this.currentReplyStatus = PingReplyStatus.TimeOut; } if (replyStatus == IPStatus.BadRoute) { this.currentReplyStatus = PingReplyStatus.UnknownHost; } } }
public MachineStatus(string machineName, bool? isActive, DateTimeOffset? lastHeard, IPStatus? pingStatus) { IsActive = isActive; LastHeard = lastHeard; PingStatus = pingStatus; MachineName = machineName; }
/// <summary> /// ping命令 /// </summary> /// <param name="ip">要ping的ip地址</param> /// <returns></returns> public static string pingC(string ip) { try { Ping ping = new Ping(); PingReply reply = ping.Send(ip); IPStatus ipStatus = reply.Status; if (ipStatus == IPStatus.Success) { return("成功"); } else if (ipStatus == IPStatus.TimedOut) { return("超时"); } else { return("失败"); } } catch (Exception e) { return(e.Message); } }
private void Search_Load(object sender, EventArgs e) { IPStatus status = IPStatus.TimedOut; try { Ping ping = new Ping(); PingReply reply = ping.Send(@"google.com"); status = reply.Status; } catch { // ignored } if (status != IPStatus.Success) { //проверка подключения к интернету DialogResult result; result = MessageBox.Show(@"Проверьте доступ к интернету!", @"Ошибка подключения!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); if (result == DialogResult.Retry) { Search_Load(sender, e); } else { Application.Exit(); } } else { form_load(); } }
public string SendEmail(string mail, string sms) { string email = "*****@*****.**"; try { Ping p = new Ping(); PingReply pr = p.Send("yandex.ru"); status = pr.Status; if (status == IPStatus.Success) { // отправитель - устанавливаем адрес и отображаемое в письме имя MailAddress from = new MailAddress(email); // кому отправляем MailAddress to = new MailAddress(mail); // создаем объект сообщения MailMessage m = new MailMessage(from, to); // текст письма m.Body = criptographs.Encryption(sms); // письмо представляет код html m.Subject = "RSA"; m.IsBodyHtml = false; // адрес smtp-сервера и порт, с которого будем отправлять письмо SmtpClient smtp = new SmtpClient("smtp.mail.ru", 25); // логин и пароль smtp.Credentials = new NetworkCredential(email, "sasha151199"); smtp.EnableSsl = true; smtp.Send(m); Console.Read(); return(m.Body); } } catch { return("Интернет отсутствует !!!"); } return("Error"); }
/// <summary> /// Sends the Ping to the current IP address and updates the /// changes /// </summary> protected void SendPing() { Ping ping = new Ping(); PingOptions options = new PingOptions(); // Set the options to the ping options.DontFragment = true; options.Ttl = PingTimeToLive; // Create the payload byte[] payloadBuffer = Encoding.ASCII.GetBytes(Payload); try { PingReply reply = ping.Send(IPAddress, PingTimeout, payloadBuffer, options); if (reply.Status == IPStatus.Success) { _lastSuccessful = DateTime.Now; _latency = (int)reply.RoundtripTime; _status = reply.Status; } else { _latency = -1; _status = reply.Status; } } catch (Exception exception) { Console.WriteLine(exception.Message); } ping.Dispose(); }
/// <summary> /// Processes the ping response. /// </summary> /// <param name="pingStatus">The ping status.</param> /// <param name="roundtripTime">The roundtrip time.</param> /// <returns>A PingCheckStatus containing the result of the Ping.</returns> public PingCheckStatus ProcessPingResponse(IPStatus pingStatus, long roundtripTime) { var status = new PingCheckStatus(); if (pingStatus == IPStatus.Success) { if ((ResponseTimeError > 0) && (roundtripTime > ResponseTimeError)) { status.Status = CheckResult.Error; status.Summary = "Ping Check Failed"; status.Details = "Response time exceeds error threshold. Response time: " + roundtripTime; } else if ((ResponseTimeWarn > 0) && (roundtripTime > ResponseTimeWarn)) { status.Status = CheckResult.Warning; status.Summary = "Ping Check Warning"; status.Details = "Response time exceeds warning threshold. Response time: " + roundtripTime; } else { status.Summary = "Ping Check Passed. Response time: " + roundtripTime; status.Status = CheckResult.Success; } } else { status.Summary = "Ping Check Failed"; status.Details = "Unsuccessful result code: " + pingStatus; status.Status = CheckResult.Error; } return(status); }
public bool run_check(string what_to_check) { bool successful_check = true; IPStatus response_code = IPStatus.Unknown; //todo:make the number of loops configurable for (int i = 1; i <= 4; i++) { response_code = ping_server(what_to_check); if (okay_responses.Contains(response_code)) { break; } } last_response = response_code.ToString(); if (okay_responses.Contains(response_code)) { failure_count = 0; Log.bound_to(this).Info("{0} was able to successfully reach {1}. Response code was {2}.", ApplicationParameters.name, what_to_check, response_code); } else { successful_check = false; failure_count += 1; Log.bound_to(this).Warn( "{0} warning! {1} is unreachable. Response code was {2}. This has happened {3} times.", ApplicationParameters.name, what_to_check, response_code, failure_count); } return(successful_check); }
public void TestConnection(int Count = 1) { Console.WriteLine("Опрашиваю узел \"" + Name + "\" [" + Address + "]. Попытка №" + Count); try { PingReply r = Program.PingSender.Send(Address, Timeout * Count, Program.packet); if (r.Status != 0) { Console.WriteLine("Ошибка: " + r.Status); if (Count == MaxCount) { Console.WriteLine("Превышено максимальное число попыток"); Status = r.Status; Ping = (int)r.RoundtripTime; } else { TestConnection(Count += 1); } } else { Status = r.Status; Ping = (int)r.RoundtripTime; } } catch (Exception e) { Status = IPStatus.Unknown; Console.WriteLine("Ошибка Ping: " + e.Message); } }
} // ///////////////////////////////////////////////////////////////// public void Add(long ms, IPStatus status) { DateTime now = DateTime.Now; if ((cnt != 0) && ( // if new minute now.Minute != prevdt.Minute || now.Hour != prevdt.Hour || now.Day != prevdt.Day || now.Month != prevdt.Month || now.Year != prevdt.Year) ) { long avg = sum / cnt; string s = prevdt.ToString("yyyy-MM-dd hh:mm") + separator + avg.ToString() + separator + success.ToString(); SaveLine(Fname, s); cnt = 1; sum = ms; success = (status == IPStatus.Success); prevdt = now; } else { cnt++; sum += ms; success = success && (status == IPStatus.Success); } } // /////////////////////////////////////////////////////////////////////////////////////
private void ShowReply(int cl, IPStatus status, long time) { switch (cl) { case 0: text[cl].Text = "Client: "; break; case 1: text[cl].Text = "Yandex: "; break; case 2: text[cl].Text = "Google: "; break; } if (status == IPStatus.Success) { text[cl].ForeColor = (time < 100) ? Color.FromArgb(0, 192, 0) : (time < 1000) ? Color.FromArgb(192, 192, 0) : Color.FromArgb(192, 0, 0); text[cl].Text += time + " ms"; } else { text[cl].ForeColor = Color.FromArgb(192, 0, 0); text[cl].Text += "No connection"; } connection[cl] = true; if (!to_close) { PingCl(ping[cl], client[cl], waiter[cl]); } }
private void blog_in_Click(object sender, RoutedEventArgs e) { Login = loginbox.Text; Password = passwordbox.Password; string hostname = "imap." + loginbox.Text.Remove(0, loginbox.Text.IndexOf('@') + 1); Hostname = hostname; IPStatus ip = IPStatus.Unknown; try { Cursor = Cursors.Wait; ip = new Ping().Send("google.com").Status; using (ImapClient client = new ImapClient(hostname, 993, loginbox.Text, passwordbox.Password, AuthMethod.Login, true)) { MainWindow m = new MainWindow(); m.Show(); Close(); } } catch { Cursor = Cursors.Arrow; if (ip == IPStatus.Success) { MessageBox.Show(data_exception); } else { MessageBox.Show(internet_exception); } } }
async Task PingTask() { Ping ping = new Ping(); status = IPStatus.Unknown; while (pingquene.Count > 5) { await Task.Delay(100); if (token.IsCancellationRequested) { return; } } pingquene.Add(ping); var pingres = await ping.SendPingAsync(_ip); pingtime = pingres.RoundtripTime; status = pingres.Status; pingquene.Remove(ping); if (token.IsCancellationRequested) { return; } Program.form1.SetItem(this); }
public PingResponse(IPAddress ipAddress, TimeSpan roundTripTime, IPStatus status, IPAddress targetIpAddress) { ReponseIpAddress = ipAddress; RoundTripTime = roundTripTime; Status = status; TargetIpAddress = targetIpAddress; }
private void RaiseOnHopFail(int hop, int retry, IPAddress address, IPStatus status) { if (OnHopFail != null) { OnHopFail(this, hop, retry, address, status); } }
private void PingerOnPingCompleted(object sender, PingCompletedEventArgs e) { int index = (int)e.UserState; if (e.Reply != null) { Ping = (int)e.Reply.RoundtripTime; PingStatus = e.Reply.Status; _last10Results[index] = e.Reply.Status == IPStatus.Success; } //if (index >= _last10Results.Length - 1) { PacketLoss = 0; for (int i = 0; i < _resultIndex; i++) { if (!_last10Results[i]) { ++PacketLoss; } } PacketLoss = (Math.Max(1, PacketLoss) / Math.Max(1, _resultIndex)) * 100; //_resultIndex = 0; } _sending = false; }
public static bool CheckPingStatus(string ipAddress) { bool pingStatus = false; IPStatus status = IPStatus.Unknown; Ping ping = null; try { ping = new Ping(); PingReply pingReply = ping.Send(ipAddress, 10000); status = pingReply.Status; if (pingReply.Status == IPStatus.Success) { pingStatus = true; } else { Logger.WriteErrorLog(string.Format("Not able to ping IP Address {0} . Ping status {1} ", ipAddress, status.ToString())); } } catch (Exception ex) { Logger.WriteErrorLog(string.Format("Not able to ping IP Address {0} . Ping status {1} ", ipAddress, status.ToString())); } finally { if (ping != null) { ping.Dispose(); } } return(pingStatus); }
internal void AddResult(PingReply res) { if (res == null) { LastStatus = IPStatus.Unknown; LastTime = TimeSpan.Zero; } else { PingsTotal++; LastStatus = res.Status; if (res.Status == IPStatus.Success) { PingsSuccessFull++; LastTime = TimeSpan.FromMilliseconds(res.RoundtripTime); if (PingsSuccessFull == 1) { AverageTime = LastTime; } else { var oldAverage = AverageTime.TotalMilliseconds; AverageTime = TimeSpan.FromMilliseconds(oldAverage + (res.RoundtripTime - oldAverage) / PingsSuccessFull); } } else { LastTime = TimeSpan.Zero; } } }
private void timer_tick() { object locker = new object(); label1.Text = label2.Text = 0.ToString(); //хожу по всем строкам dataGridView foreach (DataGridViewRow dgvR in dataGridView1.Rows) { Task.Run(async() => { //запускаю асинхронный пинг IPStatus t = await Functions.pingAsync(dataGridView1[0, dgvR.Index].Value.ToString()); if (t == IPStatus.Success) { //записую положительный результат пинга lock (locker) { dataGridView1.Rows[dgvR.Index].DefaultCellStyle.BackColor = Color.Green; label1.Text = (Convert.ToInt32(label1.Text) + 1).ToString(); } } else { //записую отрицательный результат пинга lock (locker) { dataGridView1.Rows[dgvR.Index].DefaultCellStyle.BackColor = Color.Red; label2.Text = (Convert.ToInt32(label2.Text) + 1).ToString(); } } //записую значение пинга dataGridView1[1, dgvR.Index].Value = t; }); } }
private async void Button_Click(object sender, RoutedEventArgs e) { string start = sip.Text; string end = lip.Text; byte[] sb = IPCon.GetBytes(start); byte[] eb = IPCon.GetBytes(end); flag = false; //for (byte a = sb[0]; a <= eb[0] && a <= 255; a++) // for (byte b = sb[1]; b <= eb[1] && b <= 255; b++) // for (byte c = sb[2]; c <= eb[2] && c <= 255; c++) for (byte i = sb[3]; i <= eb[3] && i <= 255; i++) { if (flag) { break; } PingReply reply = await Ping(IPCon.BytesToIP(sb[0], sb[1], sb[2], i)); string ip = reply.Address.ToString(); IPHostEntry host = Dns.GetHostEntry(IPCon.BytesToIP(sb[0], sb[1], sb[2], i)); IPStatus status = reply.Status; DataRow dr = dt.NewRow(); dr[0] = ip; dr[1] = host.HostName; dr[2] = status.ToString(); dt.Rows.Add(dr); } }
public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, string hostname, IPStatus status) { Timestamp = timestamp; IPAddress = ipAddress; Hostname = hostname; Status = status; }
public async Task Ping_IPAddress(string ipAddressString, IPStatus expected) { var ipAddress = IPAddress.Parse(ipAddressString); var status = await NetworkHelpers.PingAsync(ipAddress); Assert.Equal(expected, status); }
/// <summary> /// Constructs a new object from the IPAddress of the node and the round trip time taken /// </summary> /// <param name="count">The hop count.</param> /// <param name="address"> The IP address of the hop. </param> /// <param name="roundTripTime"> The roundtriptime it takes to the hop. </param> /// <param name="status"> The hop IP status. </param> /// <param name="time">The current time.</param> public TraceRouteHopData(Byte count, IPAddress address, Int64 roundTripTime, IPStatus status, string time) { this.Count = count; this.Address = address; this.RoundTripTime = roundTripTime; this.Status = status; this.Time = time; }
internal PingReply(uint nativeCode, int replystatus, IPAddress ipAddress, TimeSpan roundTripTime) { _nativeCode = nativeCode; _ipAddress = ipAddress; _roundTripTime = roundTripTime; if (Enum.IsDefined(typeof (IPStatus), replystatus)) _status = (IPStatus) replystatus; }
/// <summary> /// Constructs a new object from the IPAddress of the node and the round trip time taken /// </summary> /// <param name="hopCount">Number of hops to the destination</param> /// <param name="address">The IP address of the hop</param> /// <param name="roundTripTime">The roundtriptime it takes to the hop</param> /// <param name="status">The hop IP status</param> public TraceRouteHopData(Byte hopCount, IPAddress address, Int64 roundTripTime, IPStatus status, bool resolveNames) { this.Count = hopCount; this.Address = address; this.RoundTripTime = roundTripTime; this.Status = status; this.TryToResolveHostName(resolveNames); }
internal PingReply (IPAddress address, byte [] buffer, PingOptions options, long roundtripTime, IPStatus status) { this.address = address; this.buffer = buffer; this.options = options; this.rtt = roundtripTime; this.status = status; }
internal PingReply(uint nativeCode, int replystatus, IPAddress ipAddress, int roundTripTime, byte[] buffer) { _nativeCode = nativeCode; _ipAddress = ipAddress; _roundTripTime = TimeSpan.FromMilliseconds(roundTripTime); _buffer = buffer; if (Enum.IsDefined(typeof (IPStatus), replystatus)) _status = (IPStatus) replystatus; }
private string GetStatusString(IPStatus status) { switch (status) { case IPStatus.BadDestination: return "Bad destination"; case IPStatus.BadHeader: return "Invalid ICMP header"; case IPStatus.BadOption: return "Invalid ICMP option"; case IPStatus.BadRoute: return "There is no valid route to destination."; case IPStatus.DestinationHostUnreachable: return "Destination host unreachable."; case IPStatus.DestinationNetworkUnreachable: return "Destination network unreachable."; case IPStatus.DestinationPortUnreachable: return "Destination port unreachable."; case IPStatus.DestinationProtocolUnreachable: return "Destination protocol unreachable."; case IPStatus.DestinationScopeMismatch: return "Destination scope mismatch."; case IPStatus.DestinationUnreachable: return "Destination computer unreachable."; case IPStatus.HardwareError: return "Hardware error."; case IPStatus.IcmpError: return "ICMP error."; case IPStatus.NoResources: return "Insufficient network resources."; case IPStatus.PacketTooBig: return "Packet too big."; case IPStatus.ParameterProblem: return "Parameter problem"; case IPStatus.SourceQuench: return "Source quench."; case IPStatus.Success: return "Ping succeeded."; case IPStatus.TimeExceeded: return "TTL exceeded."; case IPStatus.TimedOut: return "Request timed out."; case IPStatus.TtlExpired: return "TTL expired."; case IPStatus.TtlReassemblyTimeExceeded: return "TTL reassembly time exceeded"; case IPStatus.Unknown: return "Ping failed for an unknown reason."; case IPStatus.UnrecognizedNextHeader: return "Unrecognized next header."; default: return "Ping failed."; } }
// Constructor public TraceRtNode(PingReply ping, IPHostEntry host) { hostaddr = ping.Address; status = ping.Status; if(host != null) hostname = host.HostName; else hostname = ""; roundtriptime = (int)ping.RoundtripTime; }
internal PingReply( IPAddress address, PingOptions options, IPStatus ipStatus, long rtt, byte[] buffer) { _address = address; _options = options; _ipStatus = ipStatus; _rtt = rtt; _buffer = buffer; }
// The downlevel constructor. internal PingReply (byte[] data, int dataLength, IPAddress address, int time) { this.address = address; rtt = time; ipStatus = GetIPStatus ((IcmpV4Type)data[20],(IcmpV4Code) data[21]); if (ipStatus == IPStatus.Success) { buffer = new byte[dataLength - 28]; Array.Copy (data, 28, buffer, 0, dataLength - 28); } else buffer = new byte[0]; }
internal PingReply(byte[] data, int dataLength, IPAddress address, int time) { this.address = address; this.rtt = time; this.ipStatus = this.GetIPStatus((IcmpV4Type) data[20], (IcmpV4Code) data[0x15]); if (this.ipStatus == IPStatus.Success) { this.buffer = new byte[dataLength - 0x1c]; Array.Copy(data, 0x1c, this.buffer, 0, dataLength - 0x1c); } else { this.buffer = new byte[0]; } }
internal PingReply(Icmp6EchoReply reply, IntPtr dataPtr, int sendSize) { this.address = new IPAddress(reply.Address.Address, (long) reply.Address.ScopeID); this.ipStatus = (IPStatus) reply.Status; if (this.ipStatus == IPStatus.Success) { this.rtt = reply.RoundTripTime; this.buffer = new byte[sendSize]; Marshal.Copy(IntPtrHelper.Add(dataPtr, 0x24), this.buffer, 0, sendSize); } else { this.buffer = new byte[0]; } }
// the main constructor for the icmpsendecho apis internal PingReply (IcmpEchoReply reply) { address = new IPAddress (reply.address); ipStatus = (IPStatus)reply.status; //the icmpsendecho ip status codes //only copy the data if we succeed w/ the ping operation if (ipStatus == IPStatus.Success) { rtt = (long)reply.roundTripTime; buffer = new byte[reply.dataSize]; Marshal.Copy (reply.data, buffer, 0, reply.dataSize); options = new PingOptions (reply.options); } else buffer = new byte[0]; }
internal PingReply(IcmpEchoReply reply) { address = new IPAddress((long) reply.address); ipStatus = (IPStatus) reply.status; options = new PingOptions(reply); if (this.ipStatus == IPStatus.Success) { rtt = reply.roundTripTime; buffer = new byte[reply.dataSize]; Marshal.Copy(reply.data, this.buffer, 0, reply.dataSize); } else { buffer = new byte[0]; } }
// the main constructor for the icmpsendecho apis internal PingReply (Icmp6EchoReply reply, IntPtr dataPtr, int sendSize) { address = new IPAddress(reply.Address.Address,reply.Address.ScopeID); ipStatus = (IPStatus)reply.Status; //the icmpsendecho ip status codes //only copy the data if we succeed w/ the ping operation if (ipStatus == IPStatus.Success) { rtt = (long)reply.RoundTripTime; buffer = new byte[sendSize]; Marshal.Copy (IntPtrHelper.Add(dataPtr, 36), buffer, 0, sendSize); //options = new PingOptions (reply.options); } else buffer = new byte[0]; }
private void OnReceiveServerStatus(IPStatus status) { if(status == IPStatus.Success) { this.Dispatcher.BeginInvoke(new Action(() => statusTextBlock.Text = "Server: Online")); this.Dispatcher.BeginInvoke(new Action(() => statusBorder.Background = this.Resources["onBrush"] as SolidColorBrush)); } else { this.Dispatcher.BeginInvoke(new Action(() => statusTextBlock.Text = "Server: Offline")); this.Dispatcher.BeginInvoke(new Action(() => statusBorder.Background = this.Resources["offBrush"] as SolidColorBrush)); } }
internal PingReply(Interop.IpHlpApi.Icmp6EchoReply reply, IntPtr dataPtr, int sendSize) { _address = new IPAddress(reply.Address.Address, reply.Address.ScopeID); // The icmpsendecho IP status codes. _ipStatus = (IPStatus)reply.Status; // Only copy the data if we succeed w/ the ping operation. if (_ipStatus == IPStatus.Success) { _rtt = (long)reply.RoundTripTime; _buffer = new byte[sendSize]; Marshal.Copy(IntPtrHelper.Add(dataPtr, 36), _buffer, 0, sendSize); } else { _buffer = Array.Empty<byte>(); } }
internal PingReply(Interop.IpHlpApi.IcmpEchoReply reply) { _address = new IPAddress(reply.address); // The icmpsendecho IP status codes. _ipStatus = (IPStatus)reply.status; // Only copy the data if we succeed w/ the ping operation. if (_ipStatus == IPStatus.Success) { _rtt = (long)reply.roundTripTime; _buffer = new byte[reply.dataSize]; Marshal.Copy(reply.data, _buffer, 0, reply.dataSize); _options = new PingOptions(reply.options); } else { _buffer = Array.Empty<byte>(); } }
private void ProcessHop(IPAddress address, IPStatus status) { Int64 roundTripTime = this.GetRoundtripTime(address, ref status); if (this.cancel) return; var hop = new TraceRouteHopData(counter++, address, roundTripTime, status, this.ResolveNames); lock (this.hopList) this.hopList.Add(hop); this.OnRouteHopFound(hop); this.Idle = address.Equals(this.destinationIP); lock (this.hopList) { if (!this.Idle && hopList.Count >= this.HopLimit - 1) this.ProcessHop(this.destinationIP, IPStatus.Success); } if (this.Idle) { this.OnCompleted(); this.Dispose(); } }
internal TracertNode(IPAddress address, IPStatus status, int Ttl) { _address = address; _status = status; _ttl = Ttl; }
private void RaiseOnHopFail(int hop, int retry, IPAddress address, IPStatus status) { if (OnHopFail != null) OnHopFail(this, hop, retry, address, status); }
private static bool CheckNetwork() // some implementation of network availability { IPStatus status = new IPStatus(); try { Ping p = new Ping(); PingReply pr = p.Send(@"8.8.8.8"); status = pr.Status; } catch (Exception ex) { Log.Add(ex.Message + "\r\n" + ex.Source + "\r\n" + ex.TargetSite); } if (status == IPStatus.Success) { Log.Add("Internet: true"); return true; } Log.Add("Internet: false"); return false; }
internal TracertNode(IPAddress address, long roundTripTime, IPStatus status) { _address = address; _roundTripTime = roundTripTime; _status = status; }
protected void ProcessNode(IPAddress address, IPStatus status) { long roundTripTime = 0; if (status == IPStatus.TtlExpired || status == IPStatus.Success) { var pingIntermediate = new Ping(); try { //Compute roundtrip time to the address by pinging it PingReply reply = pingIntermediate.Send(address, _timeout); roundTripTime = reply.RoundtripTime; status = reply.Status; } catch (PingException e) { //Do nothing System.Diagnostics.Trace.WriteLine(e); } finally { pingIntermediate.Dispose(); } } var node = new TracertNode(address, roundTripTime, status); lock (_nodes) { _nodes.Add(node); } if (RouteNodeFound != null) RouteNodeFound(this, new RouteNodeFoundEventArgs(node, IsDone)); IsDone = address.Equals(_destination); lock (_nodes) { if (!IsDone && _nodes.Count >= _maxHops - 1) ProcessNode(_destination, IPStatus.Success); } }
internal PingReply (IPStatus ipStatus) { this.ipStatus = ipStatus; buffer = new byte[0]; }
private void HandlePingResponse(IPStatus ipStatus) { Context.System.ActorSelection(Addresses.ConsoleWriter.Path).Tell(new MachineStatus(_machineName, false, _lastHeard, ipStatus)); Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(1), Self, new PingRequest(), Self); }
public string GetIpStatusMessage(IPStatus status) { switch (status) { case IPStatus.Success: return "successfully connected."; case IPStatus.TimedOut: return "failed to connect: Timeout."; case IPStatus.BadDestination: return "failed to connect: Bad Destination."; case IPStatus.BadHeader: return "failed to connect: Bad Header."; case IPStatus.BadOption: return "failed to connect: Bad Option."; case IPStatus.BadRoute: return "failed to connect: Bad Route."; case IPStatus.DestinationHostUnreachable: return "failed to connect: Destination Host Unreachable."; case IPStatus.DestinationNetworkUnreachable: return "failed to connect: Destination Network Unreachable."; case IPStatus.DestinationPortUnreachable: return "failed to connect: Destination Port Unreachable."; case IPStatus.DestinationProtocolUnreachable: return "failed to connect: Destination Network Unreachable."; case IPStatus.DestinationScopeMismatch: return "failed to connect: Destination Scope Mismatch."; case IPStatus.HardwareError: return "failed to connect: Hardware Error."; case IPStatus.IcmpError: return "failed to connect: ICMP Error."; case IPStatus.NoResources: return "failed to connect: No Resources."; case IPStatus.TimeExceeded: return "failed to connect: Time Exceeded."; case IPStatus.TtlExpired: return "failed to connect: TTL Expired."; case IPStatus.PacketTooBig: return "failed to connect: Packet Too Big."; case IPStatus.SourceQuench: return "failed to connect: Source Quench."; case IPStatus.TtlReassemblyTimeExceeded: return "failed to connect: TTL Reassembly Time Exceeded."; case IPStatus.ParameterProblem: return "failed to connect: IPSTATUS.PARAMETERPROBLEM ."; case IPStatus.UnrecognizedNextHeader: return "failed to connect: Unrecognized Next Header."; default: return "failed to connect: Unknown reason."; } }
private string StatusError(IPStatus status) { string text = ""; switch (status) { case IPStatus.Unknown: text = "Unknown error"; break; case IPStatus.Success: text = "Success"; break; case IPStatus.DestinationNetworkUnreachable: text = "Destination network unreachable"; break; case IPStatus.DestinationHostUnreachable: text = "Destination host unreachable"; break; case IPStatus.DestinationProtocolUnreachable: text = "Destination protocol unreachable or prohibited"; break; case IPStatus.DestinationPortUnreachable: text = "Destination port unreachable"; break; case IPStatus.NoResources: text = "No resources"; break; case IPStatus.BadOption: text = "Bad option"; break; case IPStatus.HardwareError: text = "Hardware error"; break; case IPStatus.PacketTooBig: text = "Packet too big"; break; case IPStatus.TimedOut: text = "Timed out"; break; case IPStatus.BadRoute: text = "Bad route"; break; case IPStatus.TtlExpired: text = "TTL expired"; break; case IPStatus.TtlReassemblyTimeExceeded: text = "TTL reassembly time exceeded"; break; case IPStatus.ParameterProblem: text = "Parameter problem"; break; case IPStatus.SourceQuench: text = "Source quench"; break; case IPStatus.BadDestination: text = "Bad destination"; break; case IPStatus.DestinationUnreachable: text = "Destination unreachable"; break; case IPStatus.TimeExceeded: text = "Time exceeded"; break; case IPStatus.BadHeader: text = "Bad header"; break; case IPStatus.UnrecognizedNextHeader: text = "Unrecognized next header"; break; case IPStatus.IcmpError: text = "ICMP error"; break; case IPStatus.DestinationScopeMismatch: text = "Destination scope mismatch"; break; default: text = status.ToString(); break; } return text; }
public void Ping_completed(object s, PingCompletedEventArgs e) { if (e.Reply.Status == IPStatus.Success) { _ERRCount = 0; _Status = e.Reply.Status; } else { _ERRCount++; if (_ERRCount == _RETRY) //失敗一定次數 { Write_Log(); //記錄錯誤訊息 _Status = e.Reply.Status; //變更狀態 for 閃爍 } } _isSend = false; _waitPing = 0; timer2.Enabled = true; }