Sunday, August 1, 2010

How to get Remote Machine Name

In order to get machine name or the computer name of the remote system, the system which is send some http request to your server, you just need to get IP from the request and using that IP and the InetAddress class of java.net package, we can very well get the name of that machine. Here is the code.

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

byte ipAddr[] = {0,0,0,0};
String ipAddress = req.getRemoteAddr();

if(ipAddress != null && !ipAddress.equals("")){
StringTokenizer tokenize = new StringTokenizer(ipAddress,".");

int iLen = tokenize.countTokens();

for(int i = 0 ; i < iLen;i++){
int temp = Integer.parseInt(tokenize.nextToken());
ipAddr[i] = (byte)temp;
}

InetAddress nIpAddress = InetAddress.getByAddress(ipAddr);

if(nIpAddress != null && nIpAddress.isReachable(5000) && nIpAddress.isSiteLocalAddress()){

System.out.println("Servlet - "+InetAddress.getByAddress(ipAddr).getHostName());

req.setAttribute("IP", InetAddress.getByAddress(ipAddr).getHostName());
}

}

1 comment: