Skip to content

Commit

Permalink
Add PingService
Browse files Browse the repository at this point in the history
  • Loading branch information
georg-jung committed Dec 12, 2019
1 parent be97cd0 commit 821e788
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
18 changes: 18 additions & 0 deletions WoL/Services/IPingService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System.Net;
using System.Threading.Tasks;

namespace WoL.Services
{
public interface IPingService
{
Task<bool> IsReachable(IPAddress ip, int timeout);
Task<PingResult> IsReachable(string hostname, int timeout);

public enum PingResult
{
Unreachable,
HostNotFound,
Success
}
}
}
42 changes: 42 additions & 0 deletions WoL/Services/PingService.cs
Original file line number Diff line number Diff line change
@@ -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<PingResult> 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<bool> IsReachable(IPAddress ip, int timeout)
{
using var ping = new Ping();
var reply = await ping.SendPingAsync(ip, timeout).ConfigureAwait(false);
return reply.Status == IPStatus.Success;
}
}
}
1 change: 1 addition & 0 deletions WoL/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddServerSideBlazor();
services.AddTransient<IHostService, HostService>();
services.AddTransient<IWakeService, WakeService>();
services.AddTransient<IPingService, PingService>();
services.AddTransient<IAddressLookupService, AddressLookupService>();
}

Expand Down

0 comments on commit 821e788

Please sign in to comment.