How to get Application HostName and client ip address in Java

Consider the below example,

We have an AngularJs web application and the backend is Java RESTful API.

So the application flow will be like this,
Client ==> AngularJs==> RESTful API

Assume that we have two RESTful services. They are /api/document to retrieve the document details and /api/download to download the document content in a PDF. Assume that we want to generate the download service link in the /api/document service response something like below,

/api/document?docId=1
{
	"docId": "1",
        "data":"",
	"downloadLink": "https://app-dev.com/api/download?type=pdf&docId=1"
}

Here the app-dev.com represents the host name of the application.

So to get the host name, we have to retrieve the ‘x-forward-host’  HTTP header as we can’t depend on the host header as it may be modified by the intermediate proxy server. Refer below the code to retrieve the hostname.


     public String getHost(HttpServletRequest servletRequest) {
          return servletRequest.getHeader("x-forwarded-host");
    }

To get the client IP address, we have to retrieve the ‘x-forwarded-for’ header. The general format of this field is X-Forwarded-For: client, proxy1, proxy2. So if there are any proxy servers in between the client and application, then those proxies IP address are appended to this header. So always use the first IP address available in this header to know the actual client IP address.


     public String getClientIpAddress(HttpServletRequest servletRequest) {
          return servletRequest.getHeader("X-Forwarded-For").split(",")[0];
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s