java 獲取當前網絡IP

public static String getNetIp() throws IOException {
    String url = "http://ip.chinaz.com/getip.aspx";
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        String jsonText = sb.toString();
        jsonText = jsonText.replaceAll("'", "");
        jsonText = jsonText.substring(1, jsonText.length() - 1);
        jsonText = jsonText.replaceAll(",", "<br/>");
        return jsonText;
    } finally {
        is.close();
    }
}

 

public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    System.out.println("x-forwarded-for ip: " + ip);
    if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
        // 屢次反向代理後會有多個ip值,第一個ip纔是真實ip
        if( ip.indexOf(",")!=-1 ){
            ip = ip.split(",")[0];
        }
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
        System.out.println("Proxy-Client-IP ip: " + ip);
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
        System.out.println("WL-Proxy-Client-IP ip: " + ip);
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
        System.out.println("HTTP_CLIENT_IP ip: " + ip);
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Real-IP");
        System.out.println("X-Real-IP ip: " + ip);
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
        System.out.println("getRemoteAddr ip: " + ip);
    }
    System.out.println("獲取客戶端ip: " + ip);
    return ip;
}
相關文章
相關標籤/搜索