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 { /// /// 网络操作 /// 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; } } } /// /// 获取Web客户端的Ip /// 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; } /// /// 获取远程IP /// /// 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; } /// /// 获取局域网IP /// 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; } } }