Getting Client's Address in Servlet

Getting Client's Address in Servlet


Posted in : Java Posted on : June 23, 2011 at 8:29 PM Comments : [ 0 ]

In this section we will discuss how a client's address, port number, etc can be found.

Getting Client's Address in Servlet

In this section we will discuss how a client's address, port number, etc can be found.

The example given below is described about to find the client address, port number it used etc. To accomplish these such things I used methods of ServletRequest interface and HttpServletRequest interface. Using these methods you can find the information of a client.

Exmaple : GetClientAddress.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetClientAddress extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String name = req.getParameter("name");

pw.println("<h3>You have entered name : " + name + "</h3>");

pw.println("<b>Your IP Address : <font color='blue'>" + req.getRemoteAddr()
+ "</font></b><br>");
pw.println("<b>port No. : <font color='blue'>" + req.getRemotePort()
+ "</font></b><br>");
String clientName=req.getRemoteHost();
pw.println("<b>you are hosting : <font color='blue'>" + clientName
+ "</font></b><br>");

}
}

clientAddress.html

<html>
<head>
<title>Show Client information</title>
</head>
<body>
<form method="get" action="/GetAddress/GetClientAddress">
<p>Name <input type="text" name="name"></input></p>
<p>submit<input type="submit" value="submit"></input></p>
</form>
</body>
</html>

web.xml

<web-app>
<display-name>GetAddress</display-name>
<welcome-file-list>
<welcome-file>clientAddress.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>GetClientAddress</servlet-name>
<servlet-class>GetClientAddress</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetClientAddress</servlet-name>
<url-pattern>/GetClientAddress</url-pattern>
</servlet-mapping>
</web-app>

Output : When you will execute this example you will find the following output :

After enter the name you will find the following page :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics