How to get IP address and MAC address of client in java | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

– Java access to the client IP address and MAC address

– In JSP, method to obtain the client’s IP address is: request.getRemoteAddr (), this method is effective in most cases.

– After the agent, because between the client and the service increased intermediate layer, so the server can not be directly to the IP client, server application is not directly by forwarding the requested address is returned to the client.

– But in the HTTP header information request, increase the XFORWARDEDFOR information. To track the original client IP address and the original client requests the server address.

– When we visit index.jsp/, In fact, we are not true to the browser to access the index.jsp file on the server, But the proxy server to access the index.jsp , The proxy server will access to the results returned to the browser, Because it is a proxy server to access the index.jsp, So the index.jsp through the request.getRemoteAddr () method to obtain the IP is actually the address of proxy server, Not the IP address of the client.

Then the method to obtain the real Client IP address of the client :

public String getClientIPAddress(HttpServletRequest request) { 
     if (request.getHeader("x-forwarded-for") == null) { 
          return request.getRemoteAddr(); 
     } 
     return request.getHeader("x-forwarded-for"); 
}

Access to the client MAC address

public String getClientMACAddress(String clientIp){ 
     String str = ""; 
     String macAddress = ""; 
     try { 
          Process p = Runtime.getRuntime().exec("nbtstat -A " + clientIp); 
          InputStreamReader ir = new InputStreamReader(p.getInputStream()); 
          LineNumberReader input = new LineNumberReader(ir); 
          for (int i = 1; i <100; i++) { 
               str = input.readLine(); 
               if (str != null) { 
                    if (str.indexOf("MAC Address") > 1) { 
                         macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length()); 
                         break; 
                    } 
               } 
          } 
     } catch (IOException e) { 
          e.printStackTrace(System.out); 
     } 
     return macAddress; 
}

Advertisement

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 )

Connecting to %s