獲取其它用戶的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; }