服务端:
//方法一 HttpContext.Current.Request.UserHostAddress; //方法二 HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; //方法三 string strHostName = System.Net.Dns.GetHostName(); string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString(); //方法四(忽略代理) HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
(印度)MCT Maulik Patel提供了另一种服务端的解决方法:
if(Context.Request.ServerVariables["HTTP_VIA"]!=null) // using proxy { ip=Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP. } else// not using proxy or can't get the Client IP { ip=Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP. }
以上为Asp.net(c#)的实现方法,更多编程语言请参考:http://www.west.cn/faq/list.asp?unid=405
客户端(Js):
//方法一 var ip = '<!--#echo var="REMOTE_ADDR"-->'; alert("Your IP address is "+ip); //方法二(忽略代理) function GetLocalIPAddress() { var obj = null; var rslt = ""; try { obj = new ActiveXObject("rcbdyctl.Setting"); rslt = obj.GetIPAddress; obj = null; } catch(e) { // } return rslt; }
备注:
1. 有些代理不会发送真实IP地址。
2. 有些客户端会因为“header_access deny”的安全设置而不发送IP地址。