---
title: "一段获取client端ip的代码示例"
author: "hittyt"
date: "2010-12-24T09:56:19Z"
tags: []
categories: ["编程语言"]
slug: "client-ip"
draft: false
lastmod: "2010-12-24T09:56:19Z"
id: 850840
url: "https://hittyt.iteye.com/blog/850840"
---

```
    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
     *
     * @param request 包含了http头信息
     * @return String
     */
    public static String getClientIp(HttpServletRequest request) {
        String clientIp = null;
        String strClientIp = request.getHeader("x-forwarded-for");
        if (StringUtil.isBlank(strClientIp) || StringUtil.equalsIgnoreCase(strClientIp, "unknown")) {
            clientIp = request.getRemoteAddr();
        } else {
            String[] strIps = StringUtil.split(strClientIp, ",");
            String strIp = null;
            for (int i = 0; i < strIps.length; i++) {
                strIp = strIps[i];
                if (!StringUtil.equalsIgnoreCase(strIp, "unknown")) {
                    clientIp = strIp;
                    break;
                }
            }
        }
        return clientIp;
    }
```