JAVA SERVLET - Getting the Client Requestor IP Address and or Host name
{ Posted on 12:25 PM
by Coveted
}
This is fairly simple to do, yet few know how easy it is.
The "HttpServletRequest" class has two methods that work to your advantage, as they do exactly what they specify by name.
1. getRemoteAddr() - Returns a String Object of the requesting server IP Address
2. getRemoteHost() - Returns a String Object of the requesting server HOST NAME
for example, the method below responds to POST made against the HOST server. If i wanted to print the IP Address and Host name of the requester. The code would be such.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//We will need a PrintWriter in-order to print information back to the browser without flushing an OutputStream.
PrintWriter out = resp.getWriter();
//Let's set the message String object variable with information to output.
String message = "The Requestor IP: " + req.getRemoteAddr() + " Requestor Host name: " + req.getRemoteHost();
//Set the return status to SuccessFul HTTP/1.1 200 OK
resp.setContentType("text/xml");
//Using a method of the "HttpServletResponse" class
resp.setStatus(resp.SC_OK);
//Finally output the information to the browser
out.println("");
out.println(message);
out.println("");
}
Simple and Clean



No Response to "JAVA SERVLET - Getting the Client Requestor IP Address and or Host name"
Post a Comment