java如何屏蔽ip
屏蔽IP的方法
在Java中屏蔽IP可以通过多种方式实现,具体取决于应用场景和需求。以下是几种常见的方法:
使用Servlet过滤器屏蔽IP
创建一个Servlet过滤器,检查请求的IP地址并阻止特定IP的访问:
public class IPFilter implements Filter {
private Set<String> blockedIPs = new HashSet<>();
@Override
public void init(FilterConfig filterConfig) {
blockedIPs.add("192.168.1.100");
blockedIPs.add("10.0.0.1");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String ip = request.getRemoteAddr();
if (blockedIPs.contains(ip)) {
((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
chain.doFilter(request, response);
}
}
在web.xml中配置过滤器:
<filter>
<filter-name>IPFilter</filter-name>
<filter-class>com.example.IPFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>IPFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
使用Spring Security屏蔽IP
对于Spring Boot应用,可以通过配置Security来屏蔽IP:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/")
.access("hasIpAddress('127.0.0.1') or hasIpAddress('192.168.1.0/24')")
.anyRequest().denyAll();
}
}
使用Nginx反向代理屏蔽IP
虽然这不是纯Java方案,但可以在Nginx配置中屏蔽IP:
location / {
deny 192.168.1.100;
deny 10.0.0.1;
allow all;
# Java应用的反向代理配置
proxy_pass http://localhost:8080;
}
使用Apache Commons Net检查IP范围
如果需要检查IP是否在某个范围内:
import org.apache.commons.net.util.SubnetUtils;
SubnetUtils subnet = new SubnetUtils("192.168.1.0/24");
if (subnet.getInfo().isInRange("192.168.1.100")) {
// IP在屏蔽范围内
}
使用内存数据库存储屏蔽IP
对于需要频繁更新的屏蔽列表,可以使用Redis:

Jedis jedis = new Jedis("localhost");
jedis.sadd("blocked_ips", "192.168.1.100");
// 检查IP是否被屏蔽
if (jedis.sismember("blocked_ips", ipAddress)) {
// 屏蔽该IP
}
选择哪种方法取决于具体应用场景、性能要求和系统架构。Servlet过滤器适合传统Java Web应用,Spring Security适合Spring Boot应用,而Nginx方案则可以在更底层拦截请求。






