java后台获取本地ip,访问ip,访问mac地址

InetAddress addr = InetAddress.getLocalHost();

System.out.println("获取本地ip方法:"+addr.getHostAddress());

 

System.out.println("获取外网访问ip方法一:"+request.getRemoteAddr());

 

String ipstr = request.getHeader("x-forwarded-for"); 
   if (ipstr == null || ipstr.length() == 0 || "unknown".equalsIgnoreCase(ipstr)) { 
     ipstr = request.getHeader("Proxy-Client-IP"); 
   } 
   if (ipstr == null || ipstr.length() == 0 || "unknown".equalsIgnoreCase(ipstr)) { 
     ipstr = request.getHeader("WL-Proxy-Client-IP"); 
   } 
   if (ipstr == null || ipstr.length() == 0 || "unknown".equalsIgnoreCase(ipstr)) { 
     ipstr = request.getHeader("HTTP_CLIENT_IP"); 
   } 
   if (ipstr == null || ipstr.length() == 0 || "unknown".equalsIgnoreCase(ipstr)) { 
     ipstr = request.getHeader("HTTP_X_FORWARDED_FOR"); 
   } 
   if (ipstr == null || ipstr.length() == 0 || "unknown".equalsIgnoreCase(ipstr)) { 
     ipstr = request.getRemoteAddr(); 
   } 
   System.out.println("获取外网访问ip方法二:"+ipstr);

 

System.out.println("下面是获取Mac地址等很多相关信息");

 

publicclassShowNetworkInterfaces {
    publicstaticvoidmain(String[] args)throwsException {
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while(interfaces.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface)interfaces.nextElement();
            System.out.println("=====================================");
            System.out.println(intf);
            Enumeration addresses = intf.getInetAddresses();
            while(addresses.hasMoreElements()) {
                InetAddress address = (InetAddress)addresses.nextElement();
                System.out.println(address);
            }
        }
    }

}

 

*注意以上方法可能获取的是内外ip,这是因为你是内网测试的,你用外网ip访问就获取的是外网IP了

 

正在加载评论...