O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.10. Blocking IP Addresses with a Filter

Problem

You want to use a filter that checks the IP address associated with the request.

Solution

Use a filter that calls the HttpServletRequest 's getRemoteAddr( ) method inside the doFilter( ) method and blocks the request by not calling chain.doFilter( ).

Discussion

A typical use of a filter in a web application is to check the request to make sure it's acceptable. Let's say your security division has discovered that a certain range of IP addresses represent nasty clients—you want to rebuff those folks with a "403 Forbidden" HTTP response.

Example 19-16 blocks any client IP address beginning with "192.168."

Example 19-16. A filter for blocking a certain range of IP addresses

package com.jspservletcookbook;

import java.io.IOException;import java.util.StringTokenizer;

import javax.servlet.*;
import javax.servlet.http.*;

public class IPFilter implements Filter {
    
    private FilterConfig config;
    public final static String IP_RANGE = "192.168";
    
    public IPFilter( ) {}
    
    public void  init(FilterConfig filterConfig) throws ServletException {
    
      this.config = filterConfig;
      
    }
    
    public void  doFilter(ServletRequest request, 
      ServletResponse response, 
        FilterChain chain) throws IOException, ServletException {
        
        String ip = request.getRemoteAddr( );

        HttpServletResponse httpResp = null;
        
        if (response instanceof HttpServletResponse)
            httpResp = (HttpServletResponse) response;
            
        //Break up the IP address into chunks representing each byte StringTokenizer toke = new StringTokenizer(ip,"."); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required