本文最后更新于$day天前,文中所描述的信息可能已发生改变。
正常来说只需要直接执行一段函数即可,但是如果遇到使用CDN等情况,获取到的IP就未必正确了,所以我们还需要一段函数协助我们快速获取客户端IP。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function getip() { static $ip = ''; $ip = $_SERVER['REMOTE_ADDR']; if (isset($_SERVER['HTTP_CDN_SRC_IP'])) { $ip = $_SERVER['HTTP_CDN_SRC_IP']; } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) { foreach ($matches[0] as $xip) { if (!preg_match('#^(10172\.16192\.168)\.#', $xip)) { $ip = $xip; break; } } } return $ip; }
|
以下是C#代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| protected string GetIp() { string loginip = ""; if (Request.ServerVariables["REMOTE_ADDR"] != null) { loginip = Request.ServerVariables["REMOTE_ADDR"].ToString(); } else if (Request.ServerVariables["HTTP_VIA"] != null) { if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) { loginip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); } else { loginip = Request.UserHostAddress; } } else { loginip = Request.UserHostAddress; } return loginip; }
|