根据客户端的http请求,利用request.getRemoteAddr()获取客户端Ip地址。在局域网内getRemoteAddr()和getRemoteHost()获得的结果相同。request.getRemoteAddr()是获得客户端的ip地址 。getRemoteHost()是获得客户端的主机名 。在有些场景中,可能有Squid等反向代理软件就不能获取到客户端的真实IP地址了。
经过代理以后,由于在客户端和服务之间增加了中间层,因此服务器无法直接拿到客户端的IP,服务器端应用也无法直接通过转发请求的地址返回给客户端。但是在转发请求的HTTP头信息中,增加了X-FORWARDED-FOR信息。用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址。当我们访问http://www.letu.com/index.jsp/ 时,其实并不是我们浏览器真正访问到了服务器上的index.jsp文件,而是先由代理服务器去访问http://159.226.94.32/index.jsp ,代理服务器再将访问到的结果返回给我们的浏览器,因为是代理服务器去访问index.jsp的,所以index.jsp中通过request.getRemoteAddr()的方法获取的IP实际上是代理服务器的地址,并不是客户端的IP地址。
//获取ip地址 public String getIpAddr(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 == 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; }
[root@centos-5 bin]# arp -n Address HWtype HWaddress Flags Mask Iface 159.226.94.126 ether A4:56:30:D3:5D:43 C eth0获取mac的java 代码:
import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; public class MACAddress { String ip; String mac; public MACAddress (String ip){ this.ip = ip; } public MACAddress (){ this.ip = "0.0.0.0"; } public String getMac(){ try { Process p = Runtime.getRuntime().exec("arp -n"); InputStreamReader ir = new InputStreamReader(p.getInputStream()); LineNumberReader input = new LineNumberReader(ir); p.waitFor(); boolean flag = true; String ipStr = "(" + this.ip + ")"; while(flag) { String str = input.readLine(); if (str != null) { if (str.indexOf(ipStr) > 1) { int temp = str.indexOf("at"); this.mac = str.substring( temp + 3, temp + 20); break; } } else flag = false; } } catch (IOException | InterruptedException e) { e.printStackTrace(System.out); } return this.mac; } public void setIp(String ip){ this.ip = ip; } }
java获取客户端IP地址和MAC地址,布布扣,bubuko.com
原文地址:http://blog.csdn.net/lgcssx/article/details/30253737