在做wcf时,需要得到客户端的ip。一开始用了几种方法总是不好使。后来在网上找到这个方法可以正确的获得客户端的ip了。
[OperationContract]
public static string GetClientIp()
{
string result = String.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (result != null && result != String.Empty)
{
//可¨¦能¨¹有®D代䨲理¤¨ª
if (result.IndexOf(".") == -1) //没?有®D“¡ã.”¡À肯?定¡§是º?非¤?IPv4格?式º?
result = null;
else
{
if (result.IndexOf(",") != -1)
{
//有®D“¡ã,”¡À,ê?估¨¤计?多¨¤个?代䨲理¤¨ª。¡ê取¨?第̨²一°?个?不?是º?内¨²网ª?的Ì?IP。¡ê
result = result.Replace(" ", "").Replace("'", "");
string[] temparyip = result.Split(",;".ToCharArray());
for (int i = 0; i < temparyip.Length; i++)
{
if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
{
return temparyip[i];
}
}
}
else if (IsIPAddress(result))
return result;
else
result = null;
}
}
string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (null == result || result == String.Empty)
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (result == null || result == String.Empty)
result = HttpContext.Current.Request.UserHostAddress;
return result;
}