Home » Enterprise Java » servlet » Get client’s address and hostname in Servlet

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Get client’s address and hostname in Servlet

In this example we are going to see how to get client’s address and hostname in a Servlet. Java offers a very convenient way to handle client and server information such as hostname ip address etc.

Getting a client’s address and hostname requires that you:

  • Get clients ip adfress using HttpServletRequest.getRemoteAddr().
  • Get clients hostname using HttpServletRequest.getRemoteHost().


Take a look at the code snippets that follow:
package com.javacodegeeks.snippets.enterprise;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetClientAddressAndHostnameInServlet extends HttpServlet {

	private static final long serialVersionUID = -2128122335811219481L;

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

		PrintWriter out = res.getWriter();

		// client's IP address
		String remoteAddr = req.getRemoteAddr();

		// client's hostname
		String remoteHost = req.getRemoteHost();

		out.write("remoteAddr = ");
		out.write("remoteHost = ");





<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

	<display-name>JCG Snippets Web Project</display-name>

		<servlet-name>JCG Snippets Application</servlet-name>

		<servlet-name>JCG Snippets Application</servlet-name>





remoteAddr = remoteHost = mypc

This is an example on how to get client’s address and hostname in a Servlet.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments