public SendPingAsync ( System address ) : System.Threading.Tasks.Task |
||
address | System | |
return | System.Threading.Tasks.Task |
async private void PingButton_Click(object sender, EventArgs e) { StatusLabel.Text = "Pinging…"; Ping ping = new Ping(); PingReply pingReply = await ping.SendPingAsync("yahoo.com"); StatusLabel.Text = pingReply.Status.ToString(); }
public async Task <PingReply> PingServer() { if (_pingingEndpoint) { return(await _pingSender.SendPingAsync(_serverToPing)); } else { return(await _pingSender.SendPingAsync(IPAddress.Parse(_serverToPing))); } }
/// <summary> /// Sends the ICMP echo request to the specified IP address. /// </summary> /// <param name="addressIp">A destination IP address.</param> /// <param name="timeout">Optional timeout for connection.</param> /// <returns>ICMP echo request status.</returns> public async Task<IPStatus> PingAsync(IPAddress addressIp, TimeSpan? timeout = null) { var ping = new Ping(); if (timeout.HasValue) { return await ping.SendPingAsync(addressIp, timeout.Value.Milliseconds) .ContinueWith(pingTask => pingTask.Result.Status); } return await ping.SendPingAsync(addressIp) .ContinueWith(pingTask => pingTask.Result.Status); }
async private Task SendPing(string host) { listBox1.Items.Clear(); System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); try { PingReply pr = null; for (int i = 1; i <= countTry; i++) { pr = await ping.SendPingAsync(host, delay); if (pr.Status == IPStatus.Success) { break; } await Task.Delay(5000); } listBox1.Items.Add($"{host};{pr.Status}"); progressBar1.Value++; } catch (PingException) { listBox1.Items.Add($"{host};Unknown Host"); progressBar1.Value++; } }
public static async void Send(string ip, Action <string> success, Action <string> error, int loop_qtty) { try { var ping = new Net.Ping(); var ping_response = await ping.SendPingAsync(ip); if (ping_response.Status.ToString().Equals("Success")) { success($"Iteration {loop_qtty} - Response: {ping_response.Status.ToString()}"); } else { error($"Iteration {loop_qtty} - Response: {ping_response.Status.ToString()}"); } if (loop_qtty > 1) { Send(ip, success, error, loop_qtty - 1); } } catch (Exception ex) { error($"Iteration {loop_qtty} - Error: {ex.Message}-{ex.StackTrace}"); } }
async private void PingButton_Click(object sender, EventArgs e) { List<string> urls = new List<string>() { "www.habitat-spokane.org", "www.partnersintl.org", "www.iassist.org", "www.fh.org", "www.worldvision.org" }; IPStatus status; Func<string, Task<IPStatus>> func = async (localUrl) => { Ping ping = new Ping(); PingReply pingReply = await ping.SendPingAsync(localUrl); return pingReply.Status; }; StatusLabel.Text = "Pinging…"; foreach(string url in urls) { status = await func(url); StatusLabel.Text = string.Format("{0}: {1} ({2})", url, status.ToString(), Thread.CurrentThread.ManagedThreadId); } }
public async Task <ReturnPing> getRequestPingObj(string nameOrAddress) { ReturnPing R = new ReturnPing(); try { System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); PingReply reply = await pingSender.SendPingAsync(nameOrAddress); R.PingStatus = reply.Status.ToString(); if (reply.Address != null) { R.Address = reply.Address.ToString(); } else { R.Address = "Error"; } } catch (Exception ex) { R.PingStatus = "Error: " + ex.Message; R.Address = "Error"; } return(R); }
private async void Button_Click(object sender, RoutedEventArgs e) { // Timer a = new Timer(); // //Ping pingSender = new Ping(); ////for(int i=0;i<30;i++) ////{ // // MessageBox.Show(adr); String adr ="172.16.16.10"; IPAddress address = IPAddress.Parse(adr); // // pingSender.SendAsync(address,250,new PingOptions(5,true)); // pingSender.SendAsync(address, 250); //pingSender.PingCompleted += (a, b) => //{ // if (b.Reply.Status == IPStatus.Success) // { // MessageBox.Show(b.ToString()); // } // else // { // MessageBox.Show("failed"); // } //}; //PingReply reply = await pingSender.SendPingAsync(address); //if (reply.Status == IPStatus.Success) //{ // ListBox1.Items.Add(adr); //} //else //{ // ListBox2.Items.Add("Failed "+adr); // MessageBox.Show("falied" + adr); //} //} AddressFamily d=new AddressFamily(); try { Ping s=new Ping(); var a= s.SendPingAsync(address).GetAwaiter(); a.OnCompleted(() => MessageBox.Show(a.GetResult().Status.ToString())); //UdpClient udp=new UdpClient(8080); // udp.Connect(address,8080); // var a=new byte[]{1,2}; // await udp.SendAsync(a,44); // TcpClient tcp = new TcpClient(); //await tcp.ConnectAsync(adr, 8080); // MessageBox.Show(adr); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
async private void PingButton_Click(object sender, EventArgs e) { List<string> urls = new List<string>() { "www.habitat-spokane.org", "www.partnersintl.org", "www.iassist.org", "www.fh.org", "www.worldvision.org" }; IPStatus status; Func<string, Task<IPStatus>> func = async (localUrl) => { Random random = new Random(); Ping ping = new Ping(); PingReply pingReply = await ping.SendPingAsync(localUrl); return pingReply.Status; }; StatusLabel.Text = "Pinging…"; foreach(string url in urls) { status = await func(url); StatusLabel.Text += $@"{ Environment.NewLine }{ url }: { status.ToString() } ({ Thread.CurrentThread.ManagedThreadId })"; } }
private async Task PingAsync(PingConfiguration.HostConfiguration item, CancellationToken cancellationToken) { var timeout = (int)item.Timeout.TotalMilliseconds; var hostname = item.Hostname; var alias = item.Alias; if (string.IsNullOrWhiteSpace(alias)) { alias = hostname; } var roundtripTime = item.Timeout; var status = IPStatus.Unknown; try { using var ping = new System.Net.NetworkInformation.Ping(); var pingReply = await ping.SendPingAsync(hostname, timeout); status = pingReply.Status; roundtripTime = TimeSpan.FromMilliseconds(pingReply.RoundtripTime); if (pingReply.Status == IPStatus.TimedOut) { roundtripTime = item.Timeout; } } catch (PingException ex) { if (ex.InnerException is SocketException socketException) { switch (socketException.SocketErrorCode) { case SocketError.HostNotFound: status = IPStatus.DestinationUnreachable; break; } } } catch (Exception ex) { Console.WriteLine($"Ping failed with {ex.GetType().Name}: {ex.Message}"); } await Mediator.Publish(new OutboundMeasurement() { Name = "ping", Item = new PingMeasurement() { Timestamp = DateTime.UtcNow, Source = System.Net.Dns.GetHostName(), Target = hostname, Alias = alias, Status = status, Timeout = item.Timeout, RoundtripTime = roundtripTime, }, }, cancellationToken); }
protected override async Task Handle(StatusRequest <PingHealthCheckWidget> request, CancellationToken cancellationToken) { using (var ping = new System.Net.NetworkInformation.Ping()) { var reply = await ping.SendPingAsync(request.Context.Host).ConfigureAwait(false); request.Context.Status = (reply.Status == IPStatus.Success) ? Status.OK : Status.Failed; } }
public override async Task <bool> IsReachable(IPAddress ip, TimeSpan timeout) { using (var ping = new System.Net.NetworkInformation.Ping()) { var reply = await ping.SendPingAsync(ip, (int)timeout.TotalMilliseconds).ConfigureAwait(false); return(reply.Status == IPStatus.Success); } }
public async Task<long> ping(){ _latency = long.MaxValue; try { var pingSender = new Ping(); var reply = await pingSender.SendPingAsync(uri.Host, maxTimeout); _latency = reply.Status == IPStatus.Success ? reply.RoundtripTime : long.MaxValue; } catch(PingException){ } return _latency; }
public PingWindowItem(string serverName) { Panel = new StackPanel() { Orientation = Orientation.Horizontal, }; _serverName = new Label() { Content = serverName, Width = 50, Margin = new Thickness(5, 2, 30, 2) }; _serverPing = new Label() { Content = 0, Width = 50, Margin = new Thickness(5, 2, 20, 2) }; _refreshPing = new Button() { Content = "Refresh", Width = 70, Margin = new Thickness(0, 2, 5, 2), }; _refreshPing.Click += async(sender, e) => { _serverPing.Content = "Pinging..."; using (var p = new System.Net.NetworkInformation.Ping()) { try { var pReply = await p.SendPingAsync(Utilities.GetIPToPingFromName(_serverName.Content.ToString())); if (pReply.Status == IPStatus.Success) { _serverPing.Content = pReply.RoundtripTime.ToString(); } else { _serverPing.Content = "ERROR"; } } catch { _serverPing.Content = "ERROR"; } } }; Panel.Children.Add(_serverName); Panel.Children.Add(_serverPing); Panel.Children.Add(_refreshPing); }
async Task<bool> TryPingAsync(string hostName, Ping p, ICollection<long> pings) { try { var reply = await p.SendPingAsync(hostName, DefaultTimeout).ConfigureAwait(false); if ((reply != null) && (reply.Status == IPStatus.Success)) pings.Add(reply.RoundtripTime); return true; } catch (Exception e) { this.Logger().FormattedWarnException(e); return false; } }
public async Task Handle(HealthCheckRequest <Ping> request, CancellationToken cancellationToken) { using (var ping = new System.Net.NetworkInformation.Ping()) { var reply = await ping.SendPingAsync(request.DataContext.Host) .ConfigureAwait(false); request.DataContext.State = (reply.Status == IPStatus.Success) ? State.Ok : State.Failed; } }
public override async Task<State> Poll() { var ping = new Ping(); var data = "B".PadRight(32, 'B'); var buffer = Encoding.ASCII.GetBytes(data); PingReply reply = await ping.SendPingAsync(ServerName, pingTimeout , buffer, new PingOptions(128,true)); _state = new State(); _state.Url = string.Concat(this.Name, "-", reply.Address.ToString()); _state.Status = reply.Status == IPStatus.Success ? "OK" : GetPingMessage(reply); return _state; }
private async void Run_Click(object sender, RoutedEventArgs e) { Ping Pings = new Ping(); int timeout = 500; int interval = 1000; int errors = 0; int errorLimit = 2; running = true; RunButton.Visibility = Visibility.Collapsed; StopButton.Visibility = Visibility.Visible; StatusTextBlock.Visibility = Visibility.Visible; while (running) { try { var res = await Pings.SendPingAsync("8.8.8.8", timeout); if (res.Status == IPStatus.Success) { Console("Success, time: " + res.RoundtripTime + " ms"); SetIcon("Green"); StatusTextBlock.Text = "Success"; StatusTextBlock.Foreground = System.Windows.Media.Brushes.Green; await Task.Delay(interval - (int)res.RoundtripTime); } else { errors++; if (errors >= errorLimit) { Console("Error"); SetIcon("Red"); StatusTextBlock.Text = "Error"; StatusTextBlock.Foreground = System.Windows.Media.Brushes.Red; } } } catch { errors++; if (errors >= errorLimit) { Console("Error"); SetIcon("Red"); StatusTextBlock.Text = "Error"; StatusTextBlock.Foreground = System.Windows.Media.Brushes.Red; } await Task.Delay(interval); } } SetIcon("White"); RunButton.Visibility = Visibility.Visible; StopButton.Visibility = Visibility.Collapsed; StatusTextBlock.Visibility = Visibility.Collapsed; }
public async Task PingAsync(System.Net.NetworkInformation.Ping ping, string ip) { var reply = await ping.SendPingAsync(ip, timeout); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) { lock (lockObj) { availableIpAddresses.Add(ip); } } }
private async Task PingAndUpdateAsync(System.Net.NetworkInformation.Ping ping, string ip) { var reply = await ping.SendPingAsync(ip, 500); if (reply.Status == IPStatus.Success) { TreeViewItem lb = new TreeViewItem(); lb.Header = ip; lb.Tag = "1"; nbours.Items.Add(lb); nbours.Items.Refresh(); } }
public static async Task <PhysicalAddress> PingThenTryReadFromArpTable(IPAddress ip, TimeSpan timeout) { if (!IsSupported) { throw new PlatformNotSupportedException(); } using (var ping = new System.Net.NetworkInformation.Ping()) { var reply = await ping.SendPingAsync(ip, (int)timeout.TotalMilliseconds).ConfigureAwait(false); return(await TryReadFromArpTable(ip).ConfigureAwait(false)); } }
public static async Task <bool> IsConnectedToInternet() { using (var ping = new Ping()) { try { return((await ping.SendPingAsync(ConfigurationModel.ServerIPAddress, 2000)).Status == IPStatus.Success); } catch { } } return(false); }
async private void timer1_Tick(object sender, EventArgs e) { Ping ping = new Ping(); try { await ping.SendPingAsync("github.com"); button1.Enabled = true; } catch (PingException) { button1.Enabled = false; } }
public static async Task <bool> Ping(IPAddress address, int timeout = 5000) { var pingSender = new Ping(); var buffer = Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); var options = new PingOptions(64, true); var reply = await pingSender.SendPingAsync(address, timeout, buffer, options); Debug.Log( $"Reply from {reply.Address}: bytes={reply.Buffer.Length} time={reply.RoundtripTime}ms TTL={reply.Options.Ttl}"); return(reply.Status == IPStatus.Success); }
public async Task<PingResult> PingOne(String address) { String hostname = String.Concat(address.TakeWhile(c => c != ':')); Ping pinger = new Ping(); try { PingReply reply = await pinger.SendPingAsync(hostname, 1000); return new PingResult(address, reply); } catch (PingException) { return null; } }
public static async Task<bool> CheckInternetConnectionAsync(string URL = "http://www.google.com") { Ping myPing = new Ping(); try { var pingReply = await myPing.SendPingAsync("google.com", 3000, new byte[32], new PingOptions(64, true)); if (pingReply.Status == IPStatus.Success) { return true; } } catch { return false; } return false; }
public override async Task<WorkerResult> execute() { bool pingable = false; Ping pinger = new Ping(); try { PingReply reply = await pinger.SendPingAsync(this.Address.Host); pingable = reply.Status == IPStatus.Success; return new WorkerResult() { Success = pingable, Result = reply.Buffer }; } catch (PingException e) { Debug.WriteLine("Error on pinging: " + this.Address); return new WorkerResult() { Success = false, Result = Encoding.ASCII.GetBytes(e.Message) }; } }
public static async Task <TraceRouteResult> TryTraceRouteInternalAsync(string hostNameOrAddress, int zeroBasedHop) { using (System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping()) { var hop = zeroBasedHop + 1; PingOptions pingOptions = new PingOptions(); Stopwatch stopWatch = new Stopwatch(); pingOptions.DontFragment = true; pingOptions.Ttl = hop; stopWatch.Start(); PingReply pingReply = await pingSender.SendPingAsync( hostNameOrAddress, REQUEST_TIMEOUT, _buffer, pingOptions ); stopWatch.Stop(); var elapsedMilliseconds = stopWatch.ElapsedMilliseconds; string pingReplyAddress; string strElapsedMilliseconds; if (pingReply.Status == IPStatus.TimedOut) { pingReplyAddress = STR_REQUEST_TIMEOUT; strElapsedMilliseconds = STR_REQUEST_TIME_NA; } else { pingReplyAddress = pingReply.Address.ToString(); strElapsedMilliseconds = $"{elapsedMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture)} ms"; } var traceResults = new StringBuilder(); traceResults.Append(hop.ToString(System.Globalization.CultureInfo.InvariantCulture).PadRight(4, ' ')); traceResults.Append(strElapsedMilliseconds.PadRight(10, ' ')); traceResults.Append(pingReplyAddress); return(new TraceRouteResult(traceResults.ToString(), pingReply.Status == IPStatus.Success)); } }
void ScanButton_Clicked(System.Object sender, System.EventArgs e) { Console.WriteLine("ScanButton_Clicked"); List <Task <PingReply> > tasks = new List <Task <PingReply> >(); DateTime start = DateTime.Now, end = DateTime.Now; for (int i = 0; i <= 1; ++i) { for (int j = 0; j <= 255; ++j) { var p = new System.Net.NetworkInformation.Ping(); tasks.Add(p.SendPingAsync($"192.168.{i}.{j}", 250)); Console.WriteLine($"sent ping to 192.168.{i}.{j}"); } } Task.WaitAll(tasks.ToArray()); tasks = tasks .Where(x => x.Result.Status == IPStatus.Success) .ToList(); Console.WriteLine($"number of successful pings: {tasks.Count()}"); foreach (var response in tasks) { string name = String.Empty; try { IPHostEntry host = Dns.GetHostEntry(response.Result.Address); name = host.HostName ?? String.Join(',', host.Aliases); } catch (Exception) { // do nothing } Console.WriteLine($"{response.Result.Address} -- {response.Result.Status} -- {response.Result.RoundtripTime}ms -- {name}"); this.ScanResults.Text += $"{response.Result.Address} -- {response.Result.Status} -- {response.Result.RoundtripTime}ms -- {name}\n"; } end = DateTime.Now; Console.WriteLine($"Completed in {end - start}"); this.ScanResults.Text += $"Completed in {end - start}\n"; }
static async Task ResolveAndPingAsync(string hostname, bool resolveOnly) { try { IPAddress ipToPing; string IPsCsv; if (IPAddress.TryParse(hostname, out ipToPing)) { IPsCsv = ipToPing.ToString(); #if DEBUG Console.WriteLine($"IP parsed successfully: {ipToPing} from name {hostname}"); #endif } else { #if DEBUG Console.WriteLine($"DNS lookup for: [{hostname}]"); #endif IPHostEntry entry = await Dns.GetHostEntryAsync(hostname); IPsCsv = String.Join(" ", entry.AddressList.Select(i => i.ToString())); if (resolveOnly) { Console.WriteLine($"{hostname}\t{IPsCsv}"); return; } ipToPing = entry.AddressList[0]; } PingReply reply = null; using (var ping = new System.Net.NetworkInformation.Ping()) { reply = await ping.SendPingAsync(address : ipToPing); } Console.WriteLine($"{hostname}\t{reply.Status.ToString()}\t{(reply.Status == IPStatus.Success ? IPsCsv : String.Empty)}"); } catch (Exception ex) { Console.WriteLine($"{hostname}\t{ex.Message.Replace(' ', '_')}"); } }
private async Task PingAndUpdateAsync(System.Net.NetworkInformation.Ping ping, string ip) { var reply = await ping.SendPingAsync(ip, timeout); if (reply.Status == IPStatus.Success) { lock (lockObj) { _Found++; } } else { lock (lockObj) { _nFound++; } } }
/// <summary> /// Checks machine status via ping. /// </summary> /// <returns>Empty string if machine is online, exception message if ping failed.</returns> public static async Task<string> GetMachineOnlineStatusAsync(this Uri url, int timeout = 3000) { if (url.IsFile) { return string.Empty; } try { var ping = new Ping(); var reply = await ping.SendPingAsync(url.Host, timeout); if (reply.Status != IPStatus.Success) { return reply.Status.ToString(); } } catch (PingException pex) { var pingMessage = pex.InnerException?.Message ?? pex.Message; if (!string.IsNullOrEmpty(pingMessage)) { return pingMessage; } } catch (SocketException sx) { return sx.Message; } return string.Empty; }
public static async Task StartPing(int period, string hostNameOrAddress = "ya.ru") { var pingSender = new System.Net.NetworkInformation.Ping(); Console.Clear(); Log.SendMessage($"PING {hostNameOrAddress}"); int i = 1; while (true) { var reply = await pingSender.SendPingAsync(hostNameOrAddress); var t = reply.Status; Log.SendMessage($"{reply.Buffer.Length} bytes from {reply.Address}:" + $" icmp_seq={i} status={reply.Status} time={reply.RoundtripTime}ms"); i++; if (reply.Status != IPStatus.Success) { } Thread.Sleep(period); } }
public async static Task<bool> InternetAvaliable() { Ping ping = new Ping(); try { await ping.SendPingAsync("192.168.1.1.2"); return true; } catch { return false; } }
private async Task<bool> PingRequest() { try { Ping ping = new Ping(); PingReply p = await ping.SendPingAsync(txtURL.Text, 3000); return p.Status == IPStatus.Success; } catch { return false; } }
public static async Task TestPing(string aUri) { System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping(); //pinger.PingCompleted += Pinger_PingCompleted; PingReply reply = await pinger.SendPingAsync(aUri); }
public PingItem(string serverName, string ipToPing, double xPos, double yPos) : base() { Identifier = serverName; XPos = xPos; YPos = yPos; var config = ConfigManager.GetPingConfig(); this.FontSize = config.PingFontSize; if (config.GreyBackground) { this.Background = Brushes.LightGray; } if (config.PingOutline) { this.Effect = new DropShadowEffect() { ShadowDepth = 0, BlurRadius = 2, Color = Colors.White, Opacity = 1 }; } _pingIPTimer = new System.Threading.Timer(async(state) => { using (var ping = new System.Net.NetworkInformation.Ping()) { try { var pReply = await ping.SendPingAsync(ipToPing); if (pReply.Status == IPStatus.Success) { _pingAverages.Add((int)pReply.RoundtripTime); _pingErrors = 0; } else if (pReply.Status == IPStatus.TimedOut) { _pingErrors++; } } catch { _pingErrors++; } } this.Dispatcher.Invoke(() => { // If we fail 3 pings in a row, set the ping to "ERROR" if (_pingErrors == 3) { this.Text = $"{serverName}: ERROR"; } else { if (_pingAverages.AveragePing >= 150) { this.Foreground = config.HighPingBrush; } else if (_pingAverages.AveragePing >= 80) { this.Foreground = config.MediumPingBrush; } else { this.Foreground = config.LowPingBrush; } this.Text = $"{serverName}: {_pingAverages.AveragePing}"; } }); }, null, 0, 1000); }
public async void PingAndUpdateHost(List<Host> hosts) { Ping ping = new Ping(); foreach (Host thisHost in hosts) { var reply = await ping.SendPingAsync(thisHost.ip, 1000); if (reply.Status == IPStatus.Success) { updateHostStatus(thisHost.id, "Active"); System.Threading.Thread.Sleep(100); this.SetText("Checking host health...\n" + thisHost.host_name + " is Active."); Console.WriteLine(thisHost.host_name + " is Active."); } else { updateHostStatus(thisHost.id, "Inactive"); System.Threading.Thread.Sleep(100); this.SetText("Checking host health...\n" + thisHost.host_name + " is Inactive."); Console.WriteLine(thisHost.host_name + " is Inactive."); } } //save updated host list to xml file saveXML(hostlist, sDataPath); this.metroProgressSpinner1.Visible = false; this.SetText("Checking complete."); System.Threading.Thread.Sleep(2000); this.metroButton1.Enabled = true; }
void Command_Network_Ping(PingDialog.Result result) { var replies = Task.Run(async () => { var strs = GetSelectionStrings().Select(async str => { try { using (var ping = new Ping()) { var reply = await ping.SendPingAsync(IPAddress.Parse(str), result.Timeout); return $"{str}: {reply.Status}{(reply.Status == IPStatus.Success ? $": {reply.RoundtripTime} ms" : "")}"; } } catch (Exception ex) { return $"{str}: {ex.Message}"; } }).ToList(); return await Task.WhenAll(strs); }).Result.ToList(); ReplaceSelections(replies); }
public void SendPingAsyncIPV4Succeeds() { var testIp = IPAddress.Loopback; var ping = new Ping (); var task = ping.SendPingAsync (testIp); task.Wait(); var result = task.Result; Assert.AreEqual (IPStatus.Success, result.Status); }
public void SendPingAsyncIPV4Fails() { var testIp = IPAddress.Parse("192.0.2.0"); var ping = new Ping (); var task = ping.SendPingAsync (testIp); task.Wait(); var result = task.Result; Assert.AreNotEqual (IPStatus.Success, result.Status); }
public override async Task<HealthCheckStatus> Check() { var ping = new Ping(); var result = await ping.SendPingAsync(_host, (int)_timeout.TotalMilliseconds).ConfigureAwait(false); return new HealthCheckStatus(result.Status.ToString(), result.Status != IPStatus.Success); }
/// <summary> /// Sends pings to a specified LAN-Address and checks whether it's responding or not. /// If so, the IP will be added to the main window. /// </summary> /// <returns>A boolean indicating that the task has finished.</returns> /// <param name="ipOrHost">IP-address or hostname.</param> /// <param name="totalAmountOfPings">Total amount of pings to calculate progress in main window.</param> public async Task<bool> PingAndProcessAsync(string ipOrHost, int totalAmountOfPings) { PingReply reply; // Send a asynchronous ping. using (Ping pingSender = new Ping ()) { byte[] buffer = GetPingBuffer (); int timeout = 300; var options = new PingOptions (128, true); reply = await pingSender.SendPingAsync(ipOrHost, timeout, buffer, options); } // Write ping reply (when ping completed). if (ShowDetails) { Win.InvokeLogLine (string.Format ( "{0}: {1} ({2})", ipOrHost, reply.Status.ToString () + ", RTT: " + reply.RoundtripTime, Thread.CurrentThread.ManagedThreadId) ); } // If ping was successful we add this ip to the list off online devices in main window. if (reply.Status == IPStatus.Success) { // Ad ip. Win.InvokeAddDevice (reply.Address.ToString ()); try { // Update ip with hostname var hostEntry = await Dns.GetHostEntryAsync (reply.Address); Win.InvokeUpdateDevice (reply.Address.ToString(), hostEntry.HostName); } catch(System.Net.Sockets.SocketException ex){ Win.InvokeLogLine (string.Format("{0}: {1} ({2})", "Fehler beim Auflösen des Hostnamens von", reply.Address, ex.Message)); } } // Mark progress. Win.InvokeShowProgress ((double)1 / totalAmountOfPings); // Complete task. return true; }
public static async void SinglePingCallback_Hostname() { bool callbackInvoked = false; Ping p = new Ping(); p.PingCompleted += (s, e) => callbackInvoked = true; await p.SendPingAsync(TestSettings.LocalHost); Assert.True(callbackInvoked, "Callback was not invoked."); }
public async Task<bool> PingVPNNode() { // Side-effects -> method // // BAD: An upstream network provider will recieve the ping packet and can // fingerprint/note users when not connected try { var pinger = new Ping(); var pingresult = await pinger.SendPingAsync("10.40.20.1", 700); return pingresult.Status == IPStatus.Success; } catch (PingException) { return false; } }
static void Main(string[] args) { //https://gist.github.com/fqrouter/10024379 //# ASIA //_ = '173.194.36.%s' # del 印度 新德里 //SG3 = '173.194.38.%s' # 新加坡 //TW3 = '173.194.72.%s' //SG4 = '173.194.117.%s' //JP2 = '173.194.120.%s' //_ = '173.194.123.%s' //JP1 = '173.194.126.%s' //HK1 = '173.194.127.%s' //TW1 = '74.125.23.%s' //TW2 = '74.125.31.%s' //_ = '74.125.37.%s' //_ = '74.125.135.%s' # ni //SG1 = '74.125.200.%s' //_ = '74.125.203.%s' # unknown //_ = '74.125.204.%s' # unknown //SG2 = '74.125.235.%s' //_ = '74.125.236.%s' # maa 印度 陈奈 //_ = '74.125.237.%s' # syd 澳大利亚 悉尼 //118.98.36.39 # 马来西亚 //218.189.25.167 # 香港 var dic = new Dictionary<string, int>(); for (int i = 1; i < 255; i++) { var timeout = false; for (int j = 0; j < 5; j++) { var ping = new Ping(); var ipaddress = IPAddress.Parse(string.Format("203.233.63.{0}", i)); var reply = ping.SendPingAsync(ipaddress, 5000); reply.ContinueWith(t => { if (t.Status != TaskStatus.Faulted) { var result = t.Result; if (result.Status == IPStatus.Success && result.RoundtripTime < 300) { if (j == 4) { dic.Add(result.Address.ToString(), (int)result.RoundtripTime); } Console.WriteLine(result.RoundtripTime); } else { timeout = true; Console.WriteLine(result.Status); } } else { Console.WriteLine(t.Exception); timeout = true; } }); if (timeout) { break; } } } Console.ReadKey(false); }
public async Task<ushort> SendPing() { var ping = new Ping(); var reply = await ping.SendPingAsync(EndPoint.Address); if (reply.Status != IPStatus.Success) throw new TimeoutException(); return (ushort)reply.RoundtripTime; }