伺服器資訊獲取
阿新 • • 發佈:2018-12-18
import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; public class IpUtils { /** * 獲取本機ip * * @return */ public static String getIp() { String localip = ""; try { InetAddress ip = null; ip = ip.getLocalHost(); localip = ip.getHostAddress(); } catch (Exception e) { e.printStackTrace(); } return localip; } /** * 獲取本機外網ip地址 * * @param request * @return */ public static 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; } /** * 返回本機地址(含埠) * * @param request * @return */ public static String getAddress(HttpServletRequest request) { return request.getLocalAddr() + ":" + request.getLocalPort(); } /** * 獲取請求的url地址 * @param request * @return */ public static String getServerAddress(HttpServletRequest request){ return "http://" + request.getServerName() + ":" + request.getServerPort(); } }