雖然是老生常談了,但有其用途,可以記在這。
函數及使用干脆一起列出來:
import java.net.InetAddress; import java.net.UnknownHostException; import java.time.LocalDate; import java.time.LocalTime; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class JsonCtrl { @RequestMapping(value="/sampleInterface01", method=RequestMethod.GET) public Map<String,String> getSample(HttpServletRequest rqst) { Map<String,String> map=new LinkedHashMap<>(); map.put("湖南", "岳陽"); map.put("遼寧", "大連"); map.put("time", LocalDate.now()+" "+LocalTime.now()); map.put("visitor Ip", getIp(rqst)); return map; } /** * 取得訪問者IP * @param request * @return */ public static String getIp(HttpServletRequest request) { String ipAddress = null; try { ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { // 根據網卡取本機配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 對於通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } } catch (Exception e) { ipAddress=""; } // ipAddress = this.getRequest().getRemoteAddr(); return ipAddress; } }
從其它機器訪問的效果:
由此可以看出此方法是可行的。
本機訪問則是:
出現0:0:0:0:0:0:0:1 是在服務器上訪問localhost的結果。
END