mirror of
https://gitlab.com/Hukuta47/cartrix.git
synced 2026-12-06 13:00:55 +00:00
54 lines
1.4 KiB
C#
54 lines
1.4 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)
|
|
{
|
|
IPAddress? ipv4 = Dns.GetHostAddresses(hostname)
|
|
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
|
|
|
|
if (ipv4 == null)
|
|
throw new Exception("IPv4 адрес не найден.");
|
|
|
|
return ipv4.ToString();
|
|
}
|
|
public static async Task<bool> PingHostAsync(string ipAddress)
|
|
{
|
|
try
|
|
{
|
|
using (Ping ping = new Ping())
|
|
{
|
|
PingReply reply = await ping.SendPingAsync(ipAddress, 500);
|
|
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";
|
|
}
|
|
}
|
|
}
|