package org.maggot.server.bans;
import java.util.ArrayList;
import org.maggot.server.util.Constants;
/**
* Annotations are prolly wrong, but it should work.
* @author Daniel
*/
public class AntiFlooder {
/**
* A list containing all the blocked hosts.
*/
private ArrayList<ConnectionBlock> blockedHosts;
/**
* A container for all the info needed to block the connection.
*/
private class ConnectionBlock {
private String ip;
private final long blockStart;
private int blockTime;
/**
* Sets all the variables needed.
* @param host The
* @param blockTime
*/
public ConnectionBlock(String ip, int blockTime) {
this.ip = ip;
this.blockTime = blockTime;
blockStart = System.currentTimeMillis();
}
/**
* Checks to see if the host is still blocked, if it isnt' it removes
* the block.
* @return Whether or not the host is still blocked.
*/
public boolean isHostStillBlocked() {
if(System.currentTimeMillis() - blockStart <= blockTime) {
increaseBlockTime();
return true;
}
blockedHosts.remove(this);
return false;
}
/**
* Raises the block time.
*/
private void increaseBlockTime() {
blockTime = blockTime * 2;
}
}
/**
* Sets up everything needed.
*/
public AntiFlooder() {
blockedHosts = new ArrayList<ConnectionBlock>();
}
/**
* Adds a new host to the block list.
* @param host The hosts's ip.
*/
public void blockHost(String ip) {
new ConnectionBlock(ip, Constants.FLOOD_CHECK_TIME);
}
/**
* Checks to see if the host is blocked.
* @param host The ip to check.
* @return Whether or not it's blocked.
*/
public boolean acceptConnection(String host) {
for(ConnectionBlock temp : blockedHosts)
if(temp != null)
if(temp.ip == null ? host == null : temp.ip.equals(host) && temp.isHostStillBlocked())
return false;
return true;
}
}
Custom socket class, only added a few things, nothing big. Goes with the other class in this thread.
package org.maggot.server.util;
import java.io.IOException;
import java.net.Socket;
import org.maggot.server.Main;
/**
*
* @author Daniel
*/
public class CustomSocket extends Socket {
/**
* Closes the socket and blocks any connection from that ip for a preset
* time.
*/
@Override
public void close() {
try {
Main.getAntiFlooder().blockHost(getHostAddress());
super.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Get's host address.
* @return Host's address.
*/
public String getHostAddress() {
return super.getInetAddress().getHostAddress();
}
}