1. 程式人生 > >獲取客戶端IP和本地IP的工具類

獲取客戶端IP和本地IP的工具類

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能說明:IP地址工具
 * 
 * @author LZG
 *
 */
public class IPAddressUtil {

    /**
     * 從發的request請求的頭資訊裡獲取客戶端IP地址
     * @param request
     * @return ip 客戶端IP地址
     */

    public static
String getClientIPAddress(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(); } /* * 對於通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割 "***.***.***.***".length() = 15 */
if (ip != null && ip.length() > 15) { if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } /** * 獲取本地機器IP地址 * @return 本地IP地址 */ public static String getLocalIPAddress() { InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } return inet.getHostAddress(); } //測試使用 public static void main(String[] args) { System.out.println(getLocalIPAddress()); } }