using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 网络辅助类
    /// </summary>
    public static class NetHelper
    {
        /// summary 
        /// 获取网卡硬件地址
        /// /summary 
        /// returns mac地址 /returns 
        public static string GetMacAddress()
        {
            try
            {
                //获取网卡硬件地址
                string mac = string.Empty;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"])
                    {
                        mac = mo["MacAddress"].ToString();
                        break;
                    }
                }
                moc.Dispose();
                mc.Dispose();
                moc = null;
                mc = null;

                return mac;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取一个可用的UDP端口
        /// </summary>
        /// <param name="startPort">开始端口</param>
        /// <param name="endPort">结束端口</param>
        /// <param name="notIn">端口不应该再该列表中</param>
        /// <returns>可用的UDP端口</returns>
        public static int GetAvailableUdpPort(int startPort, int endPort, List<int> notIn)
        {
            //提供本地计算机有关网络连接信息
            IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            //获取可用的UDP监听终结点信息
            IPEndPoint[] iPEndPoints = iPGlobalProperties.GetActiveUdpListeners();

            for (int port = startPort; port <= endPort; port++)
            {
                if (notIn != null && notIn.Contains(port))
                    continue;

                if (iPEndPoints.Any(p => p.Port == port))
                    continue;

                return port;
            }

            return 0;
        }
    }
}
