获取客户端IP和本地IP的工具类

来源:互联网 发布:sqlserver存储过程更新 编辑:程序博客网 时间:2024/06/11 11:06
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());    }}
0 0
原创粉丝点击