Get the IP address of the client and the MAC address summary

Source: Internet
Author: User
Tags stub stringbuffer

In a recently completed module, you need to get the system client's IP地址 and 物理地址(MAC地址) .

1. Gets the native IP and Mac is the server, not the client's →_→

Through Java, the IP address and MAC address of this machine can be completed using the following code:

Package com.howin.util; Import*;  public class Ipconfig {public static void main (string[] args) throws Exception {//TODO auto-generated method        Stub inetaddress ia=null;                         try {ia=ia.getlocalhost ();            String Localname=ia.gethostname ();            String localip=ia.gethostaddress ();            SYSTEM.OUT.PRINTLN ("The Machine name is:" + localname);        SYSTEM.OUT.PRINTLN ("The IP of this machine is:" +localip);        } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); } inetaddress ia1 = Inetaddress.getlocalhost ();//Get local IP object System.out.println ("MAC ...      "+getmacaddress (IA1)); }//Get the MAC address method private static String getmacaddress (InetAddress ia) throws exception{//Get the Network interface object (ie NIC) and get the MA          C address, the MAC address exists in a byte array.                    Byte[] mac = Networkinterface.getbyinetaddress (IA). Gethardwareaddress (); The following code is to assemble the MAC address into a string StringBuffer SB= new StringBuffer ();              for (int i=0;i<mac.length;i++) {if (i!=0) {sb.append ("-");              }//mac[i] & 0xFF is to convert byte to a positive integer String s = integer.tohexstring (Mac[i] & 0xFF);            System.out.println ("--------------");                        System.err.println (s);          Sb.append (S.length () ==1?0+s:s);      }//change all lowercase letters of the string to uppercase to become the normal MAC address and return to the return sb.tostring (). toUpperCase (); }   }

However, we should know that the Javaweb program is running on the server, which is also the IP address and MAC address of the server, not the address of the user's browser client.

2. Is it possible to get through the front-end JS?

Obviously, the Js browser client does this is forbidden, this is a terrible thing; IE's ActiveX can, but it is only ie.

In fact, we can get the client's IP address when the client browser sends the request.

3.request.getremoteaddr () method gets the client IP address
public String getRemortIP(HttpServletRequest request) {   if (request.getHeader("x-forwarded-for") == null) {     return request.getRemoteAddr();   }   return request.getHeader("x-forwarded-for"); }

The IP address of the client can be obtained by this simple method, which is valid in most cases. However, the real IP address of the client cannot be obtained through the reverse proxy software such as Apache,squid,nginx. After the agent, due to the addition of the middle tier between the client and the service, so the server can not directly get the client's IP, the server-side application can not directly forward the requested address to the client. However, the x-forwarded-for information is added to the HTTP header information of the forwarding request. Used to track the original client IP address and the server address of the original client request. When we access the resources on the server, it is not that our browser actually accesses the files on the server, but the proxy server to access the resources on the server, the proxy server and then return the results of the access to our browser, because it is the proxy server to access the server, So the IP obtained by REQUEST.GETREMOTEADDR () is actually the address of the proxy server, not the IP address of the client.

4. Multi-level agent situation
import javax.servlet.http.httpservletrequest;    /**  *  Custom Access Object tool class   *   *  get information about an object's IP address   *  @author  X-rapido  *   */  public class CusAccessObjectUtil {         /**      *  get the user real IP address, do not use REQUEST.GETREMOTEADDR (); The reason is that it is possible that the user has used the proxy software method to avoid the real IP address,      *  reference article: art/201111/305181.htm      *       *  but, If through the multi-level reverse proxy, the value of x-forwarded-for and more than one, but a string of IP values, exactly which is the real client's real IP?       *  the answer is to take the first non-unknown valid IP string in x-forwarded-for.       *       *  such as: x-forwarded-for:,,,      *      *       *  User Real IP:       *       *  @param  request       *  @return       */       public static string getipaddress (httpservletrequest request)  {           string ip = request.getheader (" X-forwarded-for ");          if  (ip == null  | |  ip.length ()  == 0 | |   "Unknown". Equalsignorecase (IP))  {               ip = request.getheader ("Proxy-client-ip");           }          if  (IP&Nbsp;== null | |  ip.length ()  == 0 | |   "Unknown". Equalsignorecase (IP))  {               ip = request.getheader ("Wl-proxy-client-ip");           }          if  (ip ==  null | |  ip.length ()  == 0 | |   "Unknown". Equalsignorecase (IP))  {               ip = request.getheader ("Http_client_ip");           }          if  (ip ==  null | |  ip.length ()  == 0 | |   "Unknown". Equalsignorecase (IP))  {               ip = request.getheader ("http_x_forwarded_for ");          }           if  (ip == null | |  ip.length ()  == 0 | |   "Unknown". Equalsignorecase (IP))  {            &NBSP;&NBSP;&NBSP;IP&NBSP;=&NBSP;REQUEST.GETREMOTEADDR ();           }          return ip;       }        }

Detailed reference:

5.Java How to get real IP after using Nginx for load
    • Analysis

As the user directly access to the Nginx,nginx again to access our Java background, if Nginx and Tomcat are on the same server, by default the use request.getRemoteAddr() of access is definitely, so the user can not get the real IP.

So how to get the real IP, the method is very simple, nginx in the client directly request when the client's IP is saved, and in the real background when the request to put the real IP into the header, and then Java to get the head.

    • Nginx Configuration

What's the specific head to go to? Sure what the head can be, but, we all have an unwritten habit, is put in X-Real-IP and, the two X-Forwarded-For seem a bit different: the former generally only store the last proxy IP, the latter will all proxy IP comma stitching up, but under normal circumstances can not use so many agents, So do not bother to control the details, specific nginx configuration as follows:

server {    listen       80;    server_name  localhost;    location / {        proxy_set_header X-Real-IP $remote_addr;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        root   html;        index  index.html;    }}
    • Java Get real IP
/** * 获取客户端IP,支持反向代理,如nginx,但不支持正向代理,比如客户端浏览器自己使用代理工具 * @param request * @return 客户端IP */public static String getClientIP(HttpServletRequest request){    String ip = request.getHeader("X-Real-IP");    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))        ip = request.getHeader("X-Forwarded-For");    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))        ip = request.getHeader("Proxy-Client-IP");    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))        ip = request.getHeader("WL-Proxy-Client-IP");    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))        ip = request.getRemoteAddr();    return ip;}



    • Http://

6. Get MAC Address

In fact we get the IP address after the MAC address is available.

On the cmd command line, we can obtain the MAC address through the nbtstat-a [IP] command.

/** * Get MAC address based on IP address * @param ipAddress * @return * @throws socketexception * @throws Unknown  Hostexception */public static string Getlocalmac (String ipAddress) throws Socketexception,unknownhostexception {//    TODO auto-generated method stub String str = "";    String macAddress = "";    Final String loopback_address = "";    If, the local MAC address is obtained.        if (Loopback_address.equals (ipAddress)) {inetaddress inetaddress = Inetaddress.getlocalhost ();        It seems that this method requires JDK1.6.        Byte[] mac = Networkinterface.getbyinetaddress (inetaddress). Gethardwareaddress ();        The following code is to assemble the MAC address into a string StringBuilder sb = new StringBuilder ();            for (int i = 0; i < mac.length; i++) {if (I! = 0) {sb.append ("-");            }//Mac[i] & 0xFF is to convert byte to a positive integer String s = integer.tohexstring (Mac[i] & 0xFF);        Sb.append (s.length () = = 1? 0 + s:s); }       Change all lowercase letters of the string to uppercase to become a regular MAC address and return macAddress = sb.tostring (). Trim (). toUpperCase ();    return macAddress;            } else {//Gets the MAC address of the non-local IP try {System.out.println (ipAddress);            Process p = runtime.getruntime (). EXEC ("nbtstat-a" + ipAddress);            System.out.println ("===process==" +p);            InputStreamReader ir = new InputStreamReader (P.getinputstream ());            BufferedReader br = new BufferedReader (IR); while ((str = br.readline ()) = null) {if (Str.indexof ("MAC") >1) {macAddress =                    Bstring (Str.indexof ("MAC") +9, Str.length ());                    MacAddress = Macaddress.trim ();                    System.out.println ("macAddress:" + macAddress);                Break            }} P.destroy ();            Br.close ();        Ir.close ();    } catch (IOException ex) {} return macAddress; }}
7. Get the MAC address problem 1. Issues not Available
    • The network cable is not connected well, first see if can ping pass

    • Whether permission to prevent external access is set in the policy group

    • Whether the firewall is blocking

    • Whether the virus, or have anti-dam system and other interception

    • Key Solutions (can ping pass but not get)

      针对这样的情况,我们可以通过ping ip之后用arp -a ip 命令来获取。

2. Is the public network feasible according to IP? Arp-a month nbtstat-a the difference?
    1. ARP can only be the same network segment (the same VLAN within the LAN).
    2. Nbtstat is a NetBIOS scan that can span network segments, but generally cannot cross LAN. (unless the other party is not directly connected to the public network via the router)

Generally speaking, according to IP check Mac basically can only check local area network.

Get the IP address of the client and the MAC address summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.