Java獲取本機IP地址

1. 通過遍歷網絡接口來獲取IP地址:

Enumeration<?> e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces();
String currentIP = "";
outer: while (e1.hasMoreElements()) {
    NetworkInterface ni = (NetworkInterface) e1.nextElement();
    String displayName = ni.getDisplayName();
    String name = ni.getName();
        if (name.indexOf("eth") < 0 && displayName.indexOf("Wireless") < 0) { // 只獲取網卡或者無線網卡的IP,根據需要配置。
            continue;
        }
    Enumeration<?> e2 = ni.getInetAddresses();
    while (e2.hasMoreElements()) {
        InetAddress ia = (InetAddress) e2.nextElement();
            if (ia instanceof Inet6Address) {
                continue;
            }
            currentIP = ia.getHostAddress();
            System.out.println(name + ">" + currentIP);
            break outer;
    }
}

2. 通過InetAddress來獲取IP地址:

InetAddress address = InetAddress.getLocalHost();  
String hostAddress = address.getHostAddress();  
System.out.println(hostAddress);  

3.過濾代理器獲取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;
	}

出處未知
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章