Java Code Examples for javax.servlet.http.HttpServletRequest#getRemoteAddr()
The following examples show how to use
javax.servlet.http.HttpServletRequest#getRemoteAddr() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IpUtils.java From NutzSite with Apache License 2.0 | 7 votes |
public static String getIpAddr(HttpServletRequest request) { if (request == null) { return "unknown"; } String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; }
Example 2
Source File: LogEventService.java From cerberus-source with GNU General Public License v3.0 | 6 votes |
@Override public void createForPrivateCalls(String page, String action, String log, HttpServletRequest request) { // Only log if cerberus_log_publiccalls parameter is equal to Y. String myUser = ""; String remoteIP = ""; String localIP = ""; if (request != null) { remoteIP = request.getRemoteAddr(); if (request.getHeader("x-forwarded-for") != null) { remoteIP = request.getHeader("x-forwarded-for"); } if (!(request.getUserPrincipal() == null)) { myUser = ParameterParserUtil.parseStringParam(request.getUserPrincipal().getName(), ""); } localIP = request.getLocalAddr(); } this.create(factoryLogEvent.create(0, 0, myUser, null, page, action, log, remoteIP, localIP)); }
Example 3
Source File: IpUtil.java From jframework with Apache License 2.0 | 6 votes |
public static String getIpAddr(HttpServletRequest request) { Objects.requireNonNull(request); String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0) { ip = request.getRemoteAddr(); } return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; }
Example 4
Source File: ToolUtil.java From mysiteforme with Apache License 2.0 | 6 votes |
/** * 获取客户端的ip信息 * * @param request * @return */ public static String getClientIp(HttpServletRequest request) { String ip = request.getHeader("X-Real-IP"); LOGGER.info("ipadd : " + ip); if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } LOGGER.info(" ip --> " + ip); return ip; }
Example 5
Source File: HttpUtils.java From utils with Apache License 2.0 | 6 votes |
/** * 如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,那么真 * 正的用户端的真实IP则是取X-Forwarded-For中第一个非unknown的有效IP字符串。 * * @param request 请求对象 * @return 真实IP */ public static String clientIP(ServletRequest request) { String ip = "127.0.0.1"; if (!(request instanceof HttpServletRequest)) { return ip; } HttpServletRequest req = (HttpServletRequest) request; ip = req.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = req.getRemoteAddr(); } return ip; }
Example 6
Source File: NetworkUtils.java From spring-boot with Apache License 2.0 | 6 votes |
public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { //多次反向代理后会有多个ip值,第一个ip才是真实ip int index = ip.indexOf(","); if (index != -1) { return ip.substring(0, index); } else { return ip; } } ip = request.getHeader("X-Real-IP"); if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { return ip; } return request.getRemoteAddr(); }
Example 7
Source File: WebUtil.java From albedo with GNU Lesser General Public License v3.0 | 6 votes |
/** * 获取ip * * @param request HttpServletRequest * @return {String} */ public String getIp(HttpServletRequest request) { Assert.notNull(request, "HttpServletRequest is null"); String ip = request.getHeader("X-Requested-For"); if (StringUtil.isBlank(ip) || CommonConstants.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (StringUtil.isBlank(ip) || CommonConstants.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtil.isBlank(ip) || CommonConstants.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtil.isBlank(ip) || CommonConstants.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (StringUtil.isBlank(ip) || CommonConstants.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtil.isBlank(ip) || CommonConstants.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return StringUtil.isBlank(ip) ? null : ip.split(",")[0]; }
Example 8
Source File: StringUtil.java From xmfcn-spring-cloud with Apache License 2.0 | 6 votes |
/** * 获取访问者IP * <p> * 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效。 * <p> * 本方法先从Header中获取X-Real-IP,如果不存在再从X-Forwarded-For获得第一个IP(用,分割), * 如果还不存在则调用Request .getRemoteAddr()。 * * @param request * @return */ public String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Real-IP"); if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) { return ip; } ip = request.getHeader("X-Forwarded-For"); if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) { // 多次反向代理后会有多个IP值,第一个为真实IP。 int index = ip.indexOf(','); if (index != -1) { return ip.substring(0, index); } else { return ip; } } else { return request.getRemoteAddr(); } }
Example 9
Source File: InMemoryThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapter.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
@Override protected String constructKey(final HttpServletRequest request) { final String username = request.getParameter(getUsernameParameter()); if (username == null) { return request.getRemoteAddr(); } return ClientInfoHolder.getClientInfo().getClientIpAddress() + ';' + username.toLowerCase(); }
Example 10
Source File: ApiProxyServlet.java From onboard with Apache License 2.0 | 5 votes |
private void setXForwardedForHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest) { String headerName = "X-Forwarded-For"; if (doForwardIP) { String newHeader = servletRequest.getRemoteAddr(); String existingHeader = servletRequest.getHeader(headerName); if (existingHeader != null) { newHeader = existingHeader + ", " + newHeader; } proxyRequest.setHeader(headerName, newHeader); } }
Example 11
Source File: CommonUtils.java From search-spring-boot-starter with Apache License 2.0 | 5 votes |
public static String getIPAddress(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip != null) { String[] ips = ip.split(","); ip = ips[0]; } if (StringUtils.isEmpty(ip)) { ip = request.getHeader("x-real-ip"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }
Example 12
Source File: UserController.java From Genesis with Apache License 2.0 | 5 votes |
/** * 获取客户端IP */ public String getRemortIP(HttpServletRequest request) { if (request.getHeader("x-forwarded-for") == null) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); }
Example 13
Source File: Dispatch.java From Almost-Famous with MIT License | 5 votes |
@RequestMapping("/a") public Resoult a(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) { Resoult r = null; try { JSONObject req = FastJsonUtils.parseObject(json); Integer cmd = req.getInteger("cmd"); Long rid = req.getLong("rid"); String token = request.getHeader("access_token"); String clientIp = request.getRemoteAddr(); // TODO 线上环境要判断uid // 仅限于robot测试使用 if (request.getHeader("uid") != null) { Long uid = Long.parseLong(request.getHeader("uid")); if (!RegisterProtocol.whiteList(cmd)) { if (!auth(uid, clientIp, token)) { return Resoult.error(0, ErrorCode.TOKEN_EXPIRE_ERROR, ""); } } } Action action = RegisterProtocol.REGISTER_PROTOCOL_MAP.get(cmd); if (Objects.isNull(action)) { log.error("Dispatch error! Unknown protocol={}", cmd); return Resoult.error(cmd, ErrorCode.UNKNOWN_PROTOCOL, ""); } if (Objects.nonNull(rid)) { action.setRid(rid); } action.setCmd(cmd); r = action.execute(req, request, response); } catch (Exception e) { log.error("", e); } return r; }
Example 14
Source File: OtpAuthenticationFilter.java From nifi with Apache License 2.0 | 5 votes |
@Override public Authentication attemptAuthentication(final HttpServletRequest request) { // only support otp login when running securely if (!request.isSecure()) { return null; } // get the accessToken out of the query string final String accessToken = request.getParameter(ACCESS_TOKEN); // if there is no authorization header, we don't know the user if (accessToken == null) { return null; } else { if (request.getContextPath().equals("/nifi-api")) { if (isDownloadRequest(request.getPathInfo())) { // handle download requests return new OtpAuthenticationRequestToken(accessToken, true, request.getRemoteAddr()); } } else { // handle requests to other context paths (other UI extensions) return new OtpAuthenticationRequestToken(accessToken, false, request.getRemoteAddr()); } // the path is a support path for otp tokens return null; } }
Example 15
Source File: ConfigServlet.java From diamond with Apache License 2.0 | 5 votes |
/** * 查找真实的IP地址 * * @param request * @return */ public String getRemortIP(HttpServletRequest request) { if (request.getHeader("x-forwarded-for") == null) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); }
Example 16
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithDefaultValues() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("protocolHeader", "x-forwarded-proto"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setSecure(true); request.setScheme("https"); request.setHeader("x-forwarded-for", "140.211.11.130"); request.setHeader("x-forwarded-proto", "http"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY boolean actualSecure = actualRequest.isSecure(); Assert.assertFalse("request must be unsecured as header x-forwarded-proto said it is http", actualSecure); String actualScheme = actualRequest.getScheme(); Assert.assertEquals("scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme); String actualRemoteAddr = actualRequest.getRemoteAddr(); Assert.assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); Assert.assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
Example 17
Source File: SecurityContext.java From NNAnalytics with Apache License 2.0 | 5 votes |
private boolean ldapLogin( HttpServletRequest request, HttpServletResponse response, String username, String password) throws HttpAction { if (ldapAuthenticator != null) { RuntimeException authFailedEx = null; Set<String> ldapBaseDns = applicationConfiguration.getLdapBaseDn(); for (String ldapBaseDn : ldapBaseDns) { String ldapDnRegexd = ldapBaseDn.replaceAll("%u", username); ldapAuthenticator.getLdapAuthenticator().setDnResolver(new FormatDnResolver(ldapDnRegexd)); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password, request.getRemoteAddr()); try { ldapAuthenticator.validate(credentials, new J2EContext(request, response)); } catch (RuntimeException e) { authFailedEx = e; continue; } LOG.debug("Login success via [LDAP] for: {} at {}", username, request.getRemoteAddr()); CommonProfile profile = credentials.getUserProfile(); profile.setId(username); String generate = jwtGenerator.generate(profile); response.addHeader("Set-Cookie", "nna-jwt-token=" + generate); currentUser.set(username); return true; } if (authFailedEx != null) { LOG.info("Login failed via [LDAP] for: {}", request.getRemoteAddr()); throw authFailedEx; } } return false; }
Example 18
Source File: AssetREST.java From ranger with Apache License 2.0 | 4 votes |
@GET @Path("/policyList/{repository}") @Encoded public String getResourceJSON(@Context HttpServletRequest request, @PathParam("repository") String repository) { String epoch = request.getParameter("epoch"); X509Certificate[] certchain = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); String ipAddress = request.getHeader("X-FORWARDED-FOR"); boolean isSecure = request.isSecure(); String policyCount = request.getParameter("policyCount"); String agentId = request.getParameter("agentId"); Long lastKnowPolicyVersion = Long.valueOf(-1); String capabilityVector = "0"; if (ipAddress == null) { ipAddress = request.getRemoteAddr(); } boolean httpEnabled = PropertiesUtil.getBooleanProperty("ranger.service.http.enabled",true); ServicePolicies servicePolicies = null; try { servicePolicies = serviceREST.getServicePoliciesIfUpdated(repository, lastKnowPolicyVersion, 0L, agentId, "", "", false, capabilityVector, request); } catch(Exception excp) { logger.error("failed to retrieve policies for repository " + repository, excp); } RangerService service = serviceUtil.getServiceByName(repository); List<RangerPolicy> policies = servicePolicies != null ? servicePolicies.getPolicies() : null; long policyUpdTime = (servicePolicies != null && servicePolicies.getPolicyUpdateTime() != null) ? servicePolicies.getPolicyUpdateTime().getTime() : 0l; VXAsset vAsset = serviceUtil.toVXAsset(service); List<VXResource> vResourceList = new ArrayList<VXResource>(); if(policies != null) { for(RangerPolicy policy : policies) { vResourceList.add(serviceUtil.toVXResource(policy, service)); } } String file = assetMgr.getLatestRepoPolicy(vAsset, vResourceList, policyUpdTime, certchain, httpEnabled, epoch, ipAddress, isSecure, policyCount, agentId); return file; }
Example 19
Source File: AgnUtils.java From openemm with GNU Affero General Public License v3.0 | 4 votes |
public static String getIpAddressForStorage(HttpServletRequest request) { String ipAddress = request.getRemoteAddr(); return ipAddress.substring(0, ipAddress.lastIndexOf(".")) + ".???"; }
Example 20
Source File: ValidationSessionInfo.java From CheckPoint with Apache License 2.0 | 2 votes |
/** * Instantiates a new Validation session info. * * @param req the req * @param t the t */ public ValidationSessionInfo(HttpServletRequest req, String t) { this.token = t; this.createDate = new Date(); this.ipAddress = req.getRemoteAddr(); }