Search code examples
javaspringspring-bootservlets

How to get client host/domain name in spring boot controller


I have a spring boot application with one rest api. Will deploy it in one linux server. And we have multiple java applications deployed in multiple linux servers calls that api. Whenever a request made to that end point, I want the host name information to validate.

  1. API - http://localhost:8000/test
  2. Second spring boot application running in 9000 port local when this application make a request to http://localhost:8000/test - I should be able to know which host made a request. here - localhost:9000

I have tried using HttpServletRequest. I'm getting only the below headers from that Host, connection, user-agent, accept, content-type, content-length. Origin , referer - headers are not present.

Controller code below

@PostMapping("/test")

public String authenticateAndGetToken (HttpServletRequest httpServletRequest, @RequestBody Request request) {

String errorMsg = "Invalid UserName";

Log.info("origin"+httpServletRequest.getHeader(HttpHeaders.ORIGIN));

httpServletRequest.getHeaderNames().asIterator().forEachRemaining (xx->System.out.println(xx));

Log.info(httpServletRequest.getRemoteAddr());

UserDetails userDetails = userInfoService. LoadUserBy Username (request.getUsername

Here origin is null Getremoteaddr is server adress not client

RestTemplate restTemplate1 = new RestTemplate(); HttpHeaders headers = new HttpHeaders();

headers.setContentType (MediaType.APPLICATION_JSON);

Map<String, String> map = new HashMap<>();

map.put("username", "test");

map.put("password", "test");

String jsonBody new ObjectMapper().writeValueAsString(map);

HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

ResponseEntity<String> response = restTemplate1.exchange(url: "http://localhost:8000/test", HttpMethod.POST, entity, String.class);

Solution

  • To get client's IP address: httpServletRequest.getRemoteAddr().

    For client's host name: InetAddress.getByName(httpServletRequest.getRemoteAddr()).getHostName(), but there could be exception to be handled.