Java Code Examples for javax.servlet.http.HttpServletRequest.getRemoteAddr()

The following are Jave code examples for showing how to use getRemoteAddr() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: springboot-shiro-cas-mybatis   File: BaseSpnegoKnownClientSystemsFilterAction.java   View Source Code Vote up 8 votes
/**
 * Pulls the remote IP from the current HttpServletRequest, or grabs the value
 * for the specified alternative attribute (say, for proxied requests).  Falls
 * back to providing the "normal" remote address if no value can be retrieved
 * from the specified alternative header value.
 * @param context the context
 * @return the remote ip
 */
private String getRemoteIp(@NotNull final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    String userAddress = request.getRemoteAddr();
    logger.debug("Remote Address = {}", userAddress);

    if (StringUtils.isNotBlank(this.alternativeRemoteHostAttribute)) {

        userAddress = request.getHeader(this.alternativeRemoteHostAttribute);
        logger.debug("Header Attribute [{}] = [{}]", this.alternativeRemoteHostAttribute, userAddress);

        if (StringUtils.isBlank(userAddress)) {
            userAddress = request.getRemoteAddr();
            logger.warn("No value could be retrieved from the header [{}]. Falling back to [{}].",
                    this.alternativeRemoteHostAttribute, userAddress);
        }
    }
    return userAddress;
}
 
Example 2
Project: zheng-lite   File: RequestUtil.java   View Source Code Vote up 7 votes
/**
 * 获取ip工具类,除了getRemoteAddr,其他ip均可伪造
 * @param request
 * @return
 */
public static String getIpAddr(HttpServletRequest request) {
	String ip = request.getHeader("Cdn-Src-Ip");    // 网宿cdn的真实ip
	if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("HTTP_CLIENT_IP");   // 蓝讯cdn的真实ip
	}
	if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("X-Forwarded-For");  // 获取代理ip
	}
	if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("Proxy-Client-IP"); // 获取代理ip
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("WL-Proxy-Client-IP"); // 获取代理ip
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getRemoteAddr(); // 获取真实ip
	}
	return ip;
}
 
Example 3
Project: tokenapp-backend   File: AddressController.java   View Source Code Vote up 7 votes
@RequestMapping(value = "/address", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE,
        produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<AddressResponse> address(@Valid @RequestBody AddressRequest addressRequest,
                                               @Valid @Size(max = Constants.UUID_CHAR_MAX_SIZE) @RequestHeader(value="Authorization") String authorizationHeader,
                                               @Context HttpServletRequest httpServletRequest)
        throws BaseException {
    // Get token
    String emailConfirmationToken = getEmailConfirmationToken(authorizationHeader);

    // Get IP address from request
    String ipAddress = httpServletRequest.getHeader("X-Real-IP");
    if (ipAddress == null)
        ipAddress = httpServletRequest.getRemoteAddr();
    LOG.info("/address called from {} with token {}, address {}, refundBTC {} refundETH {}",
            ipAddress,
            emailConfirmationToken,
            addressRequest.getAddress(),
            addressRequest.getRefundBTC(),
            addressRequest.getRefundETH());

    return setWalletAddress(addressRequest, emailConfirmationToken);
}
 
Example 4
Project: k-framework   File: CommonInterceptor.java   View Source Code Vote up 6 votes
private String getRemoteIpAddress(HttpServletRequest request) {
    String ip = request.getHeader(requestHeaderProperties.getCustomRemoteIp());
    if (null == ip || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Forwarded-For");
    }
    if (null == ip || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (null == ip || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (null == ip || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (null == ip || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (null == ip || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    return ip;
}
 
Example 5
Project: dswork   File: AuthController.java   View Source Code Vote up 6 votes
public static String getClientIp(HttpServletRequest request)
{
	String ip = request.getHeader("X-Real-IP");
	if(ip != null && ip.length() > 0 && !"null".equalsIgnoreCase(ip) && !"unKnown".equalsIgnoreCase(ip))
	{
		return ip;
	}
	ip = request.getHeader("X-Forwarded-For");
	if(ip != null && ip.length() > 0 && !"null".equalsIgnoreCase(ip) && !"unKnown".equalsIgnoreCase(ip))
	{
		// 多次反向代理后会有多个ip值,第一个ip才是真实ip
		int index = ip.indexOf(",");
		if(index != -1)
		{
			return ip.substring(0, index);
		}
		else
		{
			return ip;
		}
	}
	return request.getRemoteAddr();
}
 
Example 6
Project: rure   File: RequestUtil.java   View Source Code Vote up 6 votes
/**
 * 获取ip工具类,除了getRemoteAddr,其他ip均可伪造
 * @param request
 * @return
 */
public static String getIpAddr(HttpServletRequest request) {
	String ip = request.getHeader("Cdn-Src-Ip");    // 网宿cdn的真实ip
	if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("HTTP_CLIENT_IP");   // 蓝讯cdn的真实ip
	}
	if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("X-Forwarded-For");  // 获取代理ip
	}
	if (ip == null || ip.length() == 0 || " unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("Proxy-Client-IP"); // 获取代理ip
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("WL-Proxy-Client-IP"); // 获取代理ip
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getRemoteAddr(); // 获取真实ip
	}
	return ip;
}
 
Example 7
Project: awe-awesomesky   File: CommonUtils.java   View Source Code Vote up 5 votes
/**
 * 返回用户的IP地址
 */
public static String toIpAddr(HttpServletRequest request) {
	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("WL-Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getRemoteAddr();
	}
	return ip;
}
 
Example 8
Project: stuffEngine   File: AuditHandler.java   View Source Code Vote up 5 votes
@AfterThrowing(pointcut = "deptController() && anyMethod() " +
        "&& args(department, request)", throwing = "e")
public void handleAfterCreateDepartment(JoinPoint joinPoint,
                                        Department department, HttpServletRequest request, Throwable e) {
    int action = Integer.parseInt((((MethodSignature)joinPoint.getSignature())
            .getMethod()).getAnnotation(RequestMapping.class).name());
    AuditInfo auditRecord = new AuditInfo(department.getId(), null, request.getRemoteAddr(), department.toString(), action, e.getMessage());
    auditService.createRecord(auditRecord);
}
 
Example 9
Project: cas-server-4.2.1   File: RemoteAddressNonInteractiveCredentialsAction.java   View Source Code Vote up 5 votes
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final String remoteAddress = request.getRemoteAddr();

    if (StringUtils.hasText(remoteAddress)) {
        return new RemoteAddressCredential(remoteAddress);
    }

    logger.debug("No remote address found.");
    return null;
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: TestRemoteIpFilter.java   View Source Code Vote up 5 votes
@Test
public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithCustomValues() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("protocolHeader", "x-forwarded-proto");
    filterDef.addInitParameter("remoteIpHeader", "x-my-forwarded-for");
    filterDef.addInitParameter("httpServerPort", "8080");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setSecure(true);
    request.setScheme("https");
    request.setHeader("x-my-forwarded-for", "140.211.11.130");
    request.setHeader("x-forwarded-proto", "http");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    boolean actualSecure = actualRequest.isSecure();
    assertFalse("request must be unsecured as header x-forwarded-proto said it is http", actualSecure);

    String actualScheme = actualRequest.getScheme();
    assertEquals("scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme);

    int actualServerPort = actualRequest.getServerPort();
    assertEquals("wrong http server port", 8080, actualServerPort);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
}
 
Example 11
Project: weixinpay   File: HomeController.java   View Source Code Vote up 5 votes
public static String getIpAddr(HttpServletRequest request) {
    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("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    return ip;
}
 
Example 12
Project: backside-servlet-ks   File: BaseHandler.java   View Source Code Vote up 5 votes
public String getIpAddr(HttpServletRequest request) {      
	   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("WL-Proxy-Client-IP");      
	   }      
	   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
	       ip = request.getRemoteAddr();      
	   }      
	   return ip;      
}
 
Example 13
Project: stuffEngine   File: AuditHandler.java   View Source Code Vote up 5 votes
@AfterThrowing(pointcut = "empController() && anyMethod() &&  args(request)", throwing = "e")
public void handleAfterMethodAllEmpThrow(JoinPoint joinPoint, Throwable e, HttpServletRequest request) {
    int action = Integer.parseInt((((MethodSignature)joinPoint.getSignature())
            .getMethod()).getAnnotation(RequestMapping.class).name());

        AuditInfo auditRecord = new AuditInfo(null,null, request.getRemoteAddr(), "Get all emp", action, e.getMessage());
        auditService.createRecord(auditRecord);
}
 
Example 14
Project: jhipster-microservices-example   File: RateLimitingFilter.java   View Source Code Vote up 5 votes
/**
 * The ID that will identify the limit: the user login or the user IP address.
 */
private String getId(HttpServletRequest httpServletRequest) {
    String login = SecurityUtils.getCurrentUserLogin();
    if (login != null) {
        return login;
    } else {
        return httpServletRequest.getRemoteAddr();
    }
}
 
Example 15
Project: timesheet-upload   File: LoginController.java   View Source Code Vote up 5 votes
@GetMapping
public ModelAndView login(HttpServletRequest request) {
    log.info("Inside login method:: ");
    String ipAddress = request.getRemoteAddr();
    log.info("ipAddress from request: " + ipAddress);
    loginObj = new Login();
    loginObj.setClientIpAddress(ipAddress);
    return new ModelAndView("login", "loginObj", loginObj);
}
 
Example 16
Project: lib-edge   File: BeforeControllerAdvice.java   View Source Code Vote up 5 votes
@Around("init()")
public Object filterAroundHandling(ProceedingJoinPoint joinPoint) throws Throwable {
  log.debug("around handing");
  //action
  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
  Method action = methodSignature.getMethod();
  //接收到请求,记录请求内容
  ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  HttpServletRequest request = attributes.getRequest();
  //流控
  String clientIp = request.getRemoteAddr();
  String sessionId = request.getSession().getId();
  String requestUri = request.getRequestURI();
  String requestMethod = request.getMethod();
  long requestTimestamp = System.currentTimeMillis();
  flowControlService.flowController(clientIp, sessionId, requestUri, requestMethod, requestTimestamp, action.getDeclaredAnnotation(FlowControl.class));
  //过滤参数
  Map<String, String[]> filterParam = filterParamService.filterParam(request.getParameterMap(), action.getDeclaredAnnotation(FilterParam.class));
  //触发action, 完成参数校验部分
  Object object = joinPoint.proceed();
  log.debug("local response: {}", object);
  //透传
  PipeConfig pipeConfig = action.getAnnotation(PipeConfig.class);
  if (pipeConfig != null) {
    object = penetrationService.penetrate(request, action, methodSignature.getDeclaringType(), filterParam);
  }
  log.debug("penetration response: {}", object);
  return object;
}
 
Example 17
Project: springboot-shiro-cas-mybatis   File: RemoteAddressNonInteractiveCredentialsAction.java   View Source Code Vote up 5 votes
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final String remoteAddress = request.getRemoteAddr();

    if (StringUtils.hasText(remoteAddress)) {
        return new RemoteAddressCredential(remoteAddress);
    }

    logger.debug("No remote address found.");
    return null;
}
 
Example 18
Project: convertigo-engine   File: ServletRequester.java   View Source Code Vote up 4 votes
public void preGetDocument() throws EngineException {
	HttpServletRequest request = (HttpServletRequest) inputData;
	
	HttpUtils.checkCV(request);

	String remoteAddr = request.getRemoteAddr();
	Engine.logContext.info("Remote-Addr: \"" + remoteAddr + "\"");
	context.remoteAddr = remoteAddr;
	Log4jHelper.mdcPut(mdcKeys.ClientIP, remoteAddr);

	String remoteHost = "-";
	context.remoteHost = remoteHost;
	if (EnginePropertiesManager.getProperty(PropertyName.NET_REVERSE_DNS).equalsIgnoreCase("true")) {
		remoteHost = request.getRemoteHost();
		if (remoteHost != null) {
			context.remoteHost = remoteHost;
			Log4jHelper.mdcPut(mdcKeys.ClientHostName, context.remoteHost);
			Engine.logContext.info("Remote-Host: \"" + remoteHost + "\"");
		}
	}
	
	String contextID = context.contextID;
	Engine.logContext.debug("Context ID: " + contextID);

	String requestURI = request.getRequestURI();
	Engine.logContext.debug("Request URI: " + requestURI);

	String servletPath = request.getServletPath();
	Engine.logContext.debug("Servlet path: " + servletPath);
	context.servletPath = servletPath;

	String queryString = request.getQueryString();
	Engine.logContext.info("Query string: " + queryString);

	String userAgent = request.getHeader(HeaderName.UserAgent.value());
	Engine.logContext.info("User-Agent: \"" + userAgent + "\"");
	context.userAgent = userAgent;

	try {
		HttpSessionListener.checkSession(request);
	} catch (TASException e) {
		HttpUtils.terminateSession(request.getSession());
		throw new RuntimeException(e);
	}
}
 
Example 19
Project: raven   File: IPUtils.java   View Source Code Vote up 4 votes
/**
 * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
 * 
 * @param request
 * @return
 */
public static String getIpAddress(HttpServletRequest request)
{
    // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
    
    String ip = request.getHeader("X-Forwarded-For");
    
    try
    {
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            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("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            {
                ip = request.getRemoteAddr();
            }
        }
        else if (ip.length() > 15)
        {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++)
            {
                String strIp = (String)ips[index];
                if (!("unknown".equalsIgnoreCase(strIp)))
                {
                    ip = strIp;
                    break;
                }
            }
        }
    }
    catch (Exception e)
    {
    }
    return ip;
}
 
Example 20
Project: gitplex-mit   File: GitPostReceiveCallback.java   View Source Code Vote up 4 votes
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       String clientIp = request.getHeader("X-Forwarded-For");
       if (clientIp == null) clientIp = request.getRemoteAddr();

       if (!InetAddress.getByName(clientIp).isLoopbackAddress()) {
           response.sendError(HttpServletResponse.SC_FORBIDDEN,
                   "Git hook callbacks can only be accessed from localhost.");
           return;
       }

       List<String> fields = LoaderUtils.splitAndTrim(request.getPathInfo(), "/");
       Preconditions.checkState(fields.size() == 2);
       
       Long projectId = Long.valueOf(fields.get(0));
       Long userId = Long.valueOf(fields.get(1));
       
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       IOUtils.copy(request.getInputStream(), baos);
       
       /*
        * If multiple refs are updated, the hook stdin will put each ref update info into
        * a separate line, however the line breaks is omitted when forward the hook stdin
        * to curl via "@-", below logic is used to parse these info correctly even 
        * without line breaks.  
        */
       String callbackData = new String(baos.toByteArray());
       callbackData = StringUtils.reverse(StringUtils.remove(callbackData, '\n'));
       
       fields.clear();
       fields.addAll(LoaderUtils.splitAndTrim(callbackData, " "));
       
       unitOfWork.doAsync(new Runnable() {

		@Override
		public void run() {
			ThreadContext.bind(User.asSubject(userId));
	        try {
	            Project project = projectManager.load(projectId);
	            
		        int pos = 0;
		        while (true) {
		        	String refName = StringUtils.reverse(fields.get(pos));
		        	pos++;
		        	ObjectId newObjectId = ObjectId.fromString(StringUtils.reverse(fields.get(pos)));
		        	pos++;
		        	String field = fields.get(pos);
		        	ObjectId oldObjectId = ObjectId.fromString(StringUtils.reverse(field.substring(0, 40)));
		        	
		        	if (!newObjectId.equals(ObjectId.zeroId())) {
		        		project.cacheObjectId(refName, newObjectId);
		        	} else {
		        		newObjectId = ObjectId.zeroId();
		        		project.cacheObjectId(refName, null);
		        	}
		        	
		        	String branch = GitUtils.ref2branch(refName);
		        	if (branch != null && project.getDefaultBranch() == null) {
		        		RefUpdate refUpdate = GitUtils.getRefUpdate(project.getRepository(), "HEAD");
		        		GitUtils.linkRef(refUpdate, refName);
		        	}
		        	
		        	listenerRegistry.post(new RefUpdated(project, refName, oldObjectId, newObjectId));
		    		
		        	field = field.substring(40);
		        	if (field.length() == 0)
		        		break;
		        	else
		        		fields.set(pos, field);
		        }
	        } catch (Exception e) {
	        	logger.error("Error executing post-receive callback", e);
			} finally {
	        	ThreadContext.unbindSubject();
	        }
		}
       	
       });
}