66 lines
2.5 KiB
C#
66 lines
2.5 KiB
C#
using NLog;
|
|
using System;
|
|
using System.Configuration;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.NetworkInformation;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace PingTool
|
|
{
|
|
public static class Util
|
|
{
|
|
public static bool IsPingable(string thisPcIP, string address, int timeOut = Constant.PING_TIMEOUT_MS)
|
|
{
|
|
var pingTask = Task.Factory.StartNew(async () =>
|
|
{
|
|
bool isPingable = false;
|
|
Ping pinger = new Ping();
|
|
Logger pingLogger = LogManager.GetLogger(Constant.PING_LOGGER_FILE_NAME);
|
|
try
|
|
{
|
|
PingReply reply = await pinger.SendPingAsync(address, timeOut);
|
|
isPingable = reply.Status == IPStatus.Success;
|
|
if (!isPingable)
|
|
{
|
|
pingLogger.Log(LogLevel.Info, $"{DateTime.Now.ToString(Constant.DATETIME_FORMAT)}\tPing from {thisPcIP} to {address} status: {reply.Status}. Respone Time: {reply.RoundtripTime}");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
isPingable = false;
|
|
pingLogger.Log(LogLevel.Error, $"{DateTime.Now.ToString(Constant.DATETIME_FORMAT)}\tPing from {thisPcIP} to {address} exception: ", ex.Message);
|
|
}
|
|
finally
|
|
{
|
|
pinger.Dispose();
|
|
}
|
|
return isPingable;
|
|
});
|
|
|
|
return pingTask.Result.Result;
|
|
}
|
|
|
|
public static string GetLocalIPAddress()
|
|
{
|
|
Logger pingLogger = LogManager.GetLogger(Constant.PING_LOGGER_FILE_NAME);
|
|
try
|
|
{
|
|
string prefixIP = ConfigurationManager.AppSettings[Constant.PREFIX_IP_CONFIGURATION_KEY];
|
|
string hostName = Dns.GetHostName();
|
|
var localIPAddress = Dns.GetHostEntry(hostName)
|
|
.AddressList.Where(x => x.ToString().Contains(prefixIP))
|
|
.FirstOrDefault()
|
|
.ToString();
|
|
pingLogger.Log(LogLevel.Info, $"{DateTime.Now.ToString(Constant.DATETIME_FORMAT)}\tLocal IP Address: {localIPAddress}");
|
|
return localIPAddress;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
pingLogger.Log(LogLevel.Error, $"{DateTime.Now.ToString(Constant.DATETIME_FORMAT)}\tException message: {ex.Message}");
|
|
return string.Empty;
|
|
}
|
|
}
|
|
}
|
|
}
|