首页 > 技术文章 > 获取IP地址

flywing 原文

public static string GetIpAddress()
        {
            string ipAddress = null;
            if (HttpContext.Current != null)
            {
                ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrWhiteSpace(ipAddress))
            {
                foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return hostAddress.ToString();
                    }
                }
            }
            else
            {
                return ipAddress;
            }
            return string.Empty;
        }

推荐阅读