创建IPHelper工具类
import javax.servlet.http.HttpServletRequest;
public class IPHelper {
public static String getIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
try {
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();
}
} catch (Exception e) {
e.printStackTrace();
}
return ip;
}
}
该类获取的是ip地址如127.0.0.1这样的格式,将该地址存入数据库使用数据库INET_ATON函数
inet_aton是一个改进的方法来将一个字符串IP地址转换为一个32位的网络序列IP地址。
例:
sql = "INSERT INTO collect_pay_package(client_ip) VALUES(INET_ATON('"+ IPHelper.getIP(request)+"'))";