All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.databasesandlife.util.servlet.IpAddressDeterminer Maven / Gradle / Ivy

There is a newer version: 21.0.1
Show newest version
package com.databasesandlife.util.servlet;

import org.slf4j.LoggerFactory;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpAddressDeterminer {

    public @CheckForNull InetAddress getRequestIpAddress(@Nonnull HttpServletRequest request) {
        try {
            var ipAddress = request.getHeader("X-Forwarded-For");
            if (ipAddress == null) ipAddress = request.getRemoteAddr();
            return ipAddress == null ? null : InetAddress.getByName(ipAddress);
        }
        catch (UnknownHostException e) {
            LoggerFactory.getLogger(getClass()).warn("Unexpected exception when fetching IP address, will ignore: " + e.getMessage());
            return null;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy