Fikker首页 -> 帮助系统 -> 如何获取用户真实 IP 地址 X-Forwarded-For

特别说明:

a、Fikker 通过 HTTP 头 X-Forwarded-For 传递用户真实 IP 地址给源站,例如:X-Forwarded-For: 21.23.44.78 。
b、如果经过 Fikker 多次代理/转发,例如:X-Forwarded-For: 21.23.44.78, 156.24.66.231,这时用户真实 IP 地址一般为第一个,即 21.23.44.78 。

java 获得用户真实 IP 代码举例:

public String getRemoteIP(HttpServletRequest request)
{
    if (request.getHeader("X-Forwarded-For") == null) /* 存在 X-Forwarded-For 吗? */
    {
        return request.getRemoteAddr(); /* 兼容已有程序 */
    }
    
    return request.getHeader("X-Forwarded-For"); /* 返回用户真实 IP, 如为多个 IP 时, 则取第一个 */
}

php 获得用户真实 IP 代码举例:

function getRemoteIP()
{
    if (!isset($_SERVER["HTTP_X_FORWARDED_FOR"])) /* 存在 X-Forwarded-For 吗? */
    {
        return $_SERVER["REMOTE_ADDR"]; /* 兼容已有程序 */
    }
    
    return $_SERVER["HTTP_X_FORWARDED_FOR"]; /* 返回用户真实 IP, 如为多个 IP 时, 则取第一个 */
}

asp.net 获得用户真实 IP 代码举例:

void getRemoteIP()
{
    string SourceIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; /* 存在 X-Forwarded-For 吗? */
    if (string.IsNullOrEmpty(SourceIP))
    {
        SourceIP = Request.ServerVariables["REMOTE_ADDR"]; /* 兼容已有程序 */
    }
    
    Response.Write(SourceIP); /* 返回用户真实 IP, 如为多个 IP 时, 则取第一个 */
}

asp 获得用户真实 IP 代码举例:

<%
Private Function getRemoteIP()
Dim strIPAddr
If Request.ServerVariables("HTTP_X_FORWARDED_FOR") = "" OR InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), "unknown") > 0 Then
strIPAddr = Request.ServerVariables("REMOTE_ADDR")
ElseIf InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ",") > 0 Then
strIPAddr = Mid(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), 1, InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ",")-1)
ElseIf InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ";") > 0 Then
strIPAddr = Mid(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), 1, InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ";")-1)
Else
strIPAddr = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
End If
getIP = Trim(Mid(strIPAddr, 1, 30))
End Function

ip=getRemoteIP()
response.write(ip)
%>