using System.Net;
using System.Net.NetworkInformation;

namespace Universal;

public class NetworkAddressHelper
{
    public static List<IPAddress> GetAllIPAddress()
    {
        List<IPAddress> ipAddresses = [];

        foreach (var item in GetNetworkAdapterNames())
            ipAddresses.AddRange(GetIPAddressByAdapterName(item));

        return ipAddresses;
    }
    public static List<string> GetAllIPAddressStr()
    {
        List<string> ipAddresses = [];

        foreach (var item in GetNetworkAdapterNames())
            GetIPAddressByAdapterName(item).Foreach(t => ipAddresses.Add(t.ToString()));


        return ipAddresses;
    }


    public static List<string> GetNetworkAdapterNames()
    {
        List<string> adapterNames = [];
        NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

        foreach (NetworkInterface networkInterface in networkInterfaces)
        {
            adapterNames.Add(networkInterface.Name);
        }

        return adapterNames;
    }
    public static List<IPAddress> GetIPAddressByAdapterName(string adapterName)
    {
        List<IPAddress> ipAddresses = [];
        NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

        foreach (NetworkInterface networkInterface in networkInterfaces)
        {
            if (networkInterface.Name.Equals(adapterName, StringComparison.OrdinalIgnoreCase))
            {
                IPInterfaceProperties properties = networkInterface.GetIPProperties();
                foreach (UnicastIPAddressInformation ipAddressInfo in properties.UnicastAddresses)
                {
                    if (ipAddressInfo.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ipAddresses.Add(ipAddressInfo.Address);
                    }
                }
                break;
            }
        }

        return ipAddresses;
    }
}
