network-resurrector/NetworkResurrector.Application/Services/PingService.cs

51 lines
1.9 KiB
C#
Raw Normal View History

2020-11-28 17:03:50 +02:00
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace NetworkResurrector.Application.Services
{
public class PingService : IPingService
{
/// <summary>
/// Ping machine by IP
/// https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.ping?redirectedfrom=MSDN&view=net-5.0
/// </summary>
/// <param name="ipAddress"></param>
/// <returns>(bool success, string status)</returns>
public async Task<(bool success, string status)> PingMachine(string ipAddress)
{
var ping = new Ping();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
PingOptions options = new PingOptions
{
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 = await ping.SendPingAsync(ipAddress, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
var builder = new StringBuilder();
builder.AppendLine($"Machine '{ipAddress}' has responded to ping.");
2020-11-28 17:23:05 +02:00
builder.AppendLine($"Address: {reply.Address}");
2020-11-28 17:03:50 +02:00
builder.AppendLine($"RoundTrip time: {reply.RoundtripTime}");
builder.AppendLine($"Time to live: {reply.Options.Ttl}");
builder.AppendLine($"Don't fragment: {reply.Options.DontFragment}");
builder.AppendLine($"Buffer size: {reply.Buffer.Length}");
return (true, builder.ToString());
}
else
return (false, $"Machine '{ipAddress}' does not respond to ping. Status: {reply.Status}");
}
}
}