Files
xCommons/Helpers/XNetworkHelper.cs
T
2024-01-25 04:39:39 +03:30

81 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using xCommons.Models;
namespace xCommons.Helpers {
public static class XNetworkHelper {
/// <summary>
/// Retrieve Application Host's Machin IP Addresses ...
/// </summary>
/// <returns>string</returns>
public static string GetIp () {
//
var name = Dns.GetHostName (); // get container id
var result = Dns.GetHostEntry (name)
.AddressList
.FirstOrDefault (
x => x.AddressFamily == AddressFamily.InterNetwork
)
.MapToIPv4 ()
.ToString ();
//
return result;
}
/// <summary>
/// Retrieve All Available IP's in Application Host's Machin ...
/// </summary>
/// <returns>a Collection of XNetworkInfo class instances</returns>
public static IEnumerable<XNetworkInfo> GetNetworkInfos () {
//
var result = System.Net.NetworkInformation.NetworkInterface
.GetAllNetworkInterfaces ()
.Where (
ni =>
!ni.IsReceiveOnly &&
ni.OperationalStatus == OperationalStatus.Up &&
ni.NetworkInterfaceType != NetworkInterfaceType.Loopback
)
.SelectMany (ni =>
ni
.GetIPProperties ()
.GatewayAddresses
.Select (ga =>
new {
Name = ni.Name,
Description = ni.Description,
Gateway = ga.Address
.MapToIPv4 ()
.ToString (),
NI = ni
}
)
)
.SelectMany (data =>
data.NI
.GetIPProperties ()
.UnicastAddresses
.Select (ip =>
new XNetworkInfo {
Name = data.Name,
Gateway = data.Gateway,
Description = data.Description,
NetworkInterface = data.NI,
IP = ip.Address
.MapToIPv4 ()
.ToString ()
}
)
);
//
return result;
}
}
}