title: Limit TCP requests per IP
body: <p>I'm wondering how to limit the TCP requests per client (per specific IP) in Java. For example, I would like to allow a maximum of X requests per Y seconds for each client IP. I thought of using static Timer/TimerTask in combination with a HashSet of temporary restricted IPs.</p>
  
  <pre><code>private static final Set&lt;InetAddress&gt; restrictedIPs = Collections.synchronizedSet(new HashSet&lt;InetAddress&gt;());
  
  private static final Timer restrictTimer = new Timer();
  </code></pre>
  
  <p>So when a user connects to the server, I add his IP to the restricted list, and start a task to unrestrict him in X seconds.</p>
  
  <pre><code>restrictedIPs.add(socket.getInetAddress());
  
  restrictTimer.schedule(new TimerTask()
  {
    public void run()
    {
      restrictedIPs.remove(socket.getInetAddress());
    }
  
  },  MIN_REQUEST_INTERVAL);
  </code></pre>
  
  <p>My problem is that at the time the task will run, the socket object may be closed, and the remote IP address won't be accessible anymore...</p>
  
  <p>Any ideas welcomed! Also, if someone knows a Java-framework-built-in way to achieve this, I'd really like to hear it. </p>