获取客户端IP主机地址。
/// <summary> /// 获取客户端IP主机地址。 /// </summary> /// <returns></returns> public static string GetIP() { HttpRequest request = HttpContext.Current.Request; string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(result)) { result = request.ServerVariables["REMOTE_ADDR"]; } if (string.IsNullOrEmpty(result)) { result = request.UserHostAddress; } //最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要) string patten = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"; if (!string.IsNullOrEmpty(result) && Regex.IsMatch(result, patten)) { return result; } return "127.0.0.1"; }