From 821e788cda6e4e05a01305adcfae301186154ce2 Mon Sep 17 00:00:00 2001 From: Georg Jung Date: Thu, 12 Dec 2019 17:01:07 +0200 Subject: [PATCH] Add PingService --- WoL/Services/IPingService.cs | 18 ++++++++++++++++ WoL/Services/PingService.cs | 42 ++++++++++++++++++++++++++++++++++++ WoL/Startup.cs | 1 + 3 files changed, 61 insertions(+) create mode 100644 WoL/Services/IPingService.cs create mode 100644 WoL/Services/PingService.cs diff --git a/WoL/Services/IPingService.cs b/WoL/Services/IPingService.cs new file mode 100644 index 0000000..991d453 --- /dev/null +++ b/WoL/Services/IPingService.cs @@ -0,0 +1,18 @@ +using System.Net; +using System.Threading.Tasks; + +namespace WoL.Services +{ + public interface IPingService + { + Task IsReachable(IPAddress ip, int timeout); + Task IsReachable(string hostname, int timeout); + + public enum PingResult + { + Unreachable, + HostNotFound, + Success + } + } +} \ No newline at end of file diff --git a/WoL/Services/PingService.cs b/WoL/Services/PingService.cs new file mode 100644 index 0000000..26079a4 --- /dev/null +++ b/WoL/Services/PingService.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.Threading.Tasks; +using static WoL.Services.IPingService; + +namespace WoL.Services +{ + public class PingService : IPingService + { + private IAddressLookupService addressLookupService; + + public PingService(IAddressLookupService addressLookupService) + { + this.addressLookupService = addressLookupService; + } + + public async Task IsReachable(string hostname, int timeout) + { + await Task.Delay(1000); + IPAddress ip; + try + { + (ip, _) = await addressLookupService.GetIpAndName(hostname).ConfigureAwait(false); + } + catch + { + return PingResult.HostNotFound; + } + return await IsReachable(ip, timeout).ConfigureAwait(false) ? PingResult.Success : PingResult.Unreachable; + } + + public async Task IsReachable(IPAddress ip, int timeout) + { + using var ping = new Ping(); + var reply = await ping.SendPingAsync(ip, timeout).ConfigureAwait(false); + return reply.Status == IPStatus.Success; + } + } +} diff --git a/WoL/Startup.cs b/WoL/Startup.cs index 77c5523..3749e09 100644 --- a/WoL/Startup.cs +++ b/WoL/Startup.cs @@ -36,6 +36,7 @@ public void ConfigureServices(IServiceCollection services) services.AddServerSideBlazor(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); }