using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;
using System.Net.Sockets;

namespace ChuPiao.Common.Utils
{
    public class NetHelper
    {
        /// <summary>
        /// 获取网卡物理地址
        /// </summary>
        /// <returns></returns>
        public static string GetPhysicalAddress()
        {
            string result = "";
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                if(adapter.OperationalStatus==OperationalStatus.Up)
                {
                    // 格式化
                    PhysicalAddress pa = adapter.GetPhysicalAddress();
                    byte[] bytes = pa.GetAddressBytes();
                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < bytes.Length; i++)
                    {
                        // 以十六进制格式化
                        sb.Append(bytes[i].ToString("X2"));
                        if (i != bytes.Length - 1)
                        {
                            sb.Append("-");
                        }
                    }
                    result = sb.ToString();
                    if (result.Contains("00-00-00-00-00-00"))
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                
 
            }
            return result;

        }
        /// <summary>
        /// 获取IP 版本 4的地址
        /// </summary>
        /// <returns></returns>
        public static string GetIpAddress()
        {
            string result = "";
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                if (adapter.OperationalStatus == OperationalStatus.Up)
                {
                    UnicastIPAddressInformationCollection ipCollection = adapter.GetIPProperties().UnicastAddresses;
                    foreach (UnicastIPAddressInformation ip in ipCollection)
                    {
                        if (AddressFamily.InterNetwork == ip.Address.AddressFamily)
                        {
                            result = ip.Address.ToString();
                            return result;
                        }
                    }
                }
            }
            return result;
        }
    }
}
