mirror of
https://gitlab.com/Hukuta47/cartrix.git
synced 2026-12-05 04:20:55 +00:00
63 lines
1.7 KiB
C#
63 lines
1.7 KiB
C#
using System.Net;
|
|
using System.Net.NetworkInformation;
|
|
using System.Net.Sockets;
|
|
|
|
namespace CartriX.Api.Classes
|
|
{
|
|
public class NetworkHelper
|
|
{
|
|
public static async Task<string> GetIPFromHostnameAsync(string hostname)
|
|
{
|
|
try
|
|
{
|
|
IPAddress[] addresses = Dns.GetHostAddresses(hostname);
|
|
|
|
if (addresses.Length > 0)
|
|
{
|
|
return addresses[0].ToString();
|
|
}
|
|
|
|
return "IP адрес не найден";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return $"Ошибка: {ex.Message}";
|
|
}
|
|
}
|
|
public static async Task<bool> PingHostAsync(string ipAddress)
|
|
{
|
|
try
|
|
{
|
|
using (Ping ping = new Ping())
|
|
{
|
|
PingReply reply = ping.Send(ipAddress, 1500);
|
|
return reply.Status == IPStatus.Success;
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public static string GetLocalIp()
|
|
{
|
|
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
|
|
{
|
|
if (ni.OperationalStatus != OperationalStatus.Up) continue;
|
|
if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
|
|
|
|
var props = ni.GetIPProperties();
|
|
foreach (var ua in props.UnicastAddresses)
|
|
{
|
|
if (ua.Address.AddressFamily == AddressFamily.InterNetwork)
|
|
{
|
|
return ua.Address.ToString();
|
|
}
|
|
}
|
|
}
|
|
return "127.0.0.1";
|
|
}
|
|
}
|
|
}
|