获取其它用户的ip,可能会遇到了request.getRemoteAddr()获取的值为0:0:0:0:0:0:0:1,这是为什么呢,照道理讲,应该是127.0.0.1才对,为什么这个获取的值变成了ipv6了呢,而且我发现这种情况只有在服务器和客户端都在同一台电脑上才会出现(例如用localhost访问的时候才会出现),后来上网查了查原因,原来是/etc/hosts这个东西作怪(在windows上应该是C:\Windows\system32\drivers\etc\ hosts这个文件),只需要注释掉文件中的 # ::1 localhost 这一行即可解决问题。另外localhost这个文件很有用,这里你可以添加自己的条目,例如添加 192.168.0.212 myweb 这样子,在浏览器中原来只能使用192.168.0.212来访问的,并可以使用myweb来进行替换。
1 Loginnote loginnote = new Loginnote(); 2 // 获取ip地址 3 String ip = request.getHeader("x-forwarded-for"); 4 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 5 ip = request.getHeader("Proxy-Client-IP"); 6 } 7 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 8 ip = request.getHeader("WL-Proxy-Client-IP"); 9 }10 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {11 ip = request.getHeader("HTTP_CLIENT_IP");12 }13 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {14 ip = request.getHeader("HTTP_X_FORWARDED_FOR");15 }16 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {17 ip = request.getRemoteAddr();18 }19 System.out.println(ip);20 // 因为有些有些登录是通过代理,所以取第一个(第一个为真是ip)21 int index = ip.indexOf(',');22 if (index != -1) {23 ip = ip.substring(0, index);24 }
如果只需要获取自己的ip,所有人登录都显示服务器的ip的话
1 2 InetAddress netAddress = getInetAddress(); 3 //调用以下代码 4 5 6 private InetAddress getInetAddress() { try { return 7 InetAddress.getLocalHost(); } catch (UnknownHostException e) { 8 System.out.println("不知道ip地址"); } return null; } 9 10 private static String getHostIp(InetAddress netAddress) { if (null ==11 netAddress) { return null; } String ip = netAddress.getHostAddress();//12 * 获取ip return ip; }