I am wondering how to limit TCP requests to one client (per specific IP) in Java. For example, I would like to allow a maximum of X requests in Y seconds for each client IP address. I was thinking about using a static timer / TimerTask in combination with a HashSet of temporary restricted IP addresses.
private static final Set<InetAddress> restrictedIPs = Collections.synchronizedSet(new HashSet<InetAddress>()); private static final Timer restrictTimer = new Timer();
Therefore, when a user connects to the server, I add his IP address to the list of restrictions and run the task to restrict it for X seconds.
restrictedIPs.add(socket.getInetAddress()); restrictTimer.schedule(new TimerTask() { public void run() { restrictedIPs.remove(socket.getInetAddress()); } }, MIN_REQUEST_INTERVAL);
My problem is that during the execution of the task, the socket object may be closed and the remote IP address will no longer be available ...
Any ideas are welcome! Also, if someone knows the Java-framework-built-in way to achieve this, I would really love to hear it.
source share