using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;

namespace Nirvana.Common
{
    /// <summary>
    /// 网络操作
    /// </summary>
    public class Net
    {
        public static string Ip
        {
            get
            {
                try
                {
                    var result = string.Empty;
                    if (MyHttpContext.current != null)
                        result = GetWebClientIp();
                    if (string.IsNullOrWhiteSpace(result))
                        result = GetLanIp();
                    return result;
                }
                catch (System.Exception)
                {

                    return string.Empty;
                }
            }
        }


        /// <summary>
        /// 获取Web客户端的Ip
        /// </summary>
        private static string GetWebClientIp()
        {
            var ip = GetWebRemoteIp();
            foreach (var hostAddress in Dns.GetHostAddresses(ip))
            {
                if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                    return hostAddress.ToString();
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取远程IP
        /// </summary>
        /// <returns></returns>
        private static string GetWebRemoteIp()
        {
            var ip =  MyHttpContext.current.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = MyHttpContext.current.Connection.RemoteIpAddress.ToString();
            }
            return ip;
        }

        /// <summary>
        /// 获取局域网IP
        /// </summary>
        private static string GetLanIp()
        {
            string userIP = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
  .Select(p => p.GetIPProperties())
  .SelectMany(p => p.UnicastAddresses)
  .Where(p => p.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !System.Net.IPAddress.IsLoopback(p.Address))
  .FirstOrDefault()?.Address.ToString();

            return userIP;
        }

    }

}
