JAVA工具–通过HttpServletRequest获取IP
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
public class IpUtils {
private static final Logger logger = Logger.getLogger(IpUtils.class.getName());
private static String LOCAL_IP_STAR_STR = "192.168.";
static {
String ip = null;
String hostName = null;
try {
hostName = InetAddress.getLocalHost().getHostName();
InetAddress[] ipAddrs = InetAddress.getAllByName(hostName);
for (InetAddress ipAddr : ipAddrs) {
if (ipAddr.getHostAddress().startsWith(LOCAL_IP_STAR_STR)) {
break;
}
}
if (ip == null) {
ip = ipAddrs[0].getHostAddress();
}
} catch (UnknownHostException e) {
logger.severe("IpUtils error.");
}
LOCAL_IP = ip;
HOST_NAME = hostName;
}
public static final String LOCAL_IP;
public static final String HOST_NAME;
public static String getIpAddr(HttpServletRequest request) {
String unknown = "unknown";
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();
if (ip.equals("127.0.0.1")) {
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ip = inet.getHostAddress();
} catch (UnknownHostException e) {
logger.severe("IpHelper error." + e.toString());
}
}
}
int ipMaxLength = 15;
if (ip != null && ip.length() > ipMaxLength) {
return ip.substring(0, ip.indexOf(","));
}
return ip;
}
}