您的位置:首页 > 其它

MINA源码分析----怎么设置IP限制的(防火墙)

2014-12-03 17:19 363 查看
主要涉及到以下两个类  

一个是IP子网类  (IPV4)

package org.apache.mina.filter.firewall;

import java.net.Inet4Address;
import java.net.InetAddress;

/**
* A IP subnet using the CIDR notation符号.     无类域内路由选择(Classless Inter-Domain Routing)
Currently, only IP version 4
* address are supported.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class Subnet {
/**有符号数,这里最高位为1,即负数,负数在计算机中是以补码表示的!!
* 例如    IP_MASK = 0x80000000 ,是以补码形式表示的负数 ,其原码为    0x80000000  减1取反 ,最高位不变
*      同理  若  IP_MASK = 0x80000010  ,则其表示的负数  为   0x80000001 减 1取反,最高位为1
*      即    0xffffffff  才是其真正表示的负数,这才是我们平时做题计算用的形式 ,与计算机中存储的形式不同!!
*/
private static final int IP_MASK = 0x80000000;//凡是在程序中表示的二进制数都表示计算机中的存储,是补码
private static final int BYTE_MASK = 0xFF;

private InetAddress subnet;//子网IP
private int subnetInt;//IP的整数表示
private int subnetMask;//子网掩码
private int suffix;//后缀

/**
* Creates a subnet from CIDR notation. For example, the subnet
* 192.168.0.0/24 would be created using the {@link InetAddress}
* 192.168.0.0 and the mask 24.
* @param subnet The {@link InetAddress} of the subnet
* @param mask The mask
*
* 192.168.0.0/24这是IP地址的一个规范写法,前面是IP地址,
* 后面跟一个斜杠以及一个数字,这条斜杠及后面的数字称为网络掩码(network mask)。
* 斜杠后面的数字表示有意义的比特位的个数(从左到右)。
* 例如IP地址:255.255.255.255是IPv4中最大可能的IP地址,
* 每个数字(255)都是由8个比特位表示的,每个比特位非0即1,最大值即为11111111,即28=256(0-255)。
* 了解了IP地址之后,就很容易理解上述的写法了。
* 比如192.168.0.0/24中的24表示从左到右的24位(也就是前24位)有效,那么剩下的8位可以是任意数值,
* 可以是0-254之间的任一地址(255为广播地址)。同样192.168.0.0/32也很好理解,
* 就是上述IP地址的前32位有效,也就是所有的位都是有效的,即为192.168.0.0。
*/
public Subnet(InetAddress subnet, int mask) {
if(subnet == null) {
throw new IllegalArgumentException("Subnet address can not be null");
}
if(!(subnet instanceof Inet4Address)) {
throw new IllegalArgumentException("Only IPv4 supported");
}

if(mask < 0 || mask > 32) {
throw new IllegalArgumentException("Mask has to be an integer between 0 and 32");
}

this.subnet = subnet;
this.subnetInt = toInt(subnet);
this.suffix = mask;

// binary mask for this subnet 二进制掩码
/** 这里的右移是有符号右移,最高位仍是1,即为负数,负数在计算机中是以补码表示的
* ,例如假设计算机为8位的处理器,-5用二进制表示为1000 0101  ,
*   但是在计算机中的存储则为 1000 0101的补码,即为  1111 1011 ,这一点要搞清楚
*
*   并且在java中>>表示带符号右移 ,右移后最高位补1
*   >>>表示无符号右移,右移后最高位补0
*
*   IP_MASK >> (24-1) ,表示带符号右移23位 ,则this.subnetMask 的16制为0xffff ff00
*/
this.subnetMask = IP_MASK >> (mask - 1);//负数10100110 >>5(假设字长为8位),则得到的是 11111101
//符号位向右移动后,正数的话补0,负数补1,也就是汇编语言中的算术右移.
//同样当移动的位数超过类型的长度时,会取余数,然后移动余数个位
/**
System.out.println((0x80000000>>30));
/**
* java中>>表示带符号右移 ,(0x80000000>>30)右移30位,
* 在计算机表示为11111111111111111111111111111110,但是在输出时为-2,
* 也说明了在计算机中作移位运算是对数的补码作移位运算,正数的补码为其自身,要注意的是负数补码
*/
/**	int a = (0x80000000>>30) ;//11111111111111111111111111111110
int b = 0x80000000;
System.out.println(b);//输出-2147483648
for(int i=0;i<32;i++){
if((a&b)!=0)
System.out.print("1" );
else
System.out.println("0");
b=b>>>1;//无符号右移
}   http://blog.csdn.net/gaochizhen33/article/details/7161417 System.out.println(b);//输出0
*/
}

/**
* Converts an IP address into an integer
*/
private int toInt(InetAddress inetAddress) {
byte[] address = inetAddress.getAddress();
int result = 0;//例如把134.168.98.75转换为int型,32位,每一部分有8位
for (int i = 0; i < address.length; i++) {//一字节8位
result <<= 8;//左移8位
result |= address[i] & BYTE_MASK;
}
return result;
}

/**
* Converts an IP address to a subnet using the provided
* mask
* @param address The address to convert into a subnet
* @return The subnet as an integer
*/
private int toSubnet(InetAddress address) {
return toInt(address) & subnetMask;
//IP地址与子网掩码相与得到该IP地址的网络地址,最下面有解释
}

/**
* Checks if the {@link InetAddress} is within this subnet
* @param address The {@link InetAddress} to check
* @return True if the address is within this subnet, false otherwise
*/
public boolean inSubnet(InetAddress address) {
//判断该IP是否在本网段内
return toSubnet(address) == subnetInt;
}

/**
* @see Object#toString()
*/
@Override
public String toString() {
return subnet.getHostAddress() + "/" + suffix;
}

@Override
public boolean equals(Object obj) {
if(!(obj instanceof Subnet)) {
return false;
}

Subnet other = (Subnet) obj;

return other.subnetInt == subnetInt && other.suffix == suffix;
}

}
/**
回答1:
IP地址218.17.209.0/24不能说"0/24"的意思是什么.这里面的0是与前面的三个十进制数是一体的,是个IP地址,
也就是218.17.209.0.在这里是指一个网段.  "/24"是指掩码的位数是二进制的24位,也就是十进制的255.255.255.0
/24可以理解为从0-255的所有IP地址,其中0为网络地址,255为广播地址.

回答2:
192.168.0.1/24
24的意思就是说子网掩码中表示网络的二进制位数是24位,即: 11111111.11111111.11111111.00000000
数一下看是不是24个1,变成十进制就是:255.255.255.0
如果把前面的IP也变成二进制数,即:
11000000.10101000.00000000.00000001 (192.168.0.1)
11111111.11111111.11111111.00000000 (255.255.255.0)
将两者做'与'运算得:
11000000.10101000.00000000.00000000
再变成十进制数得:
192.168.0.0
这个就是192.168.0.1这个IP所属的网络地址,也可以说192.168.0.1在192.168.0.0这个网段内。

24表示这个IP的子网掩码是255.255.255.0
子网掩码可以表示子网的大小。
如192.168.0.0/24 表示这个IP范围为
192.168.0.1-192.168.0.254

*/


另一个就是限制IP访问的过滤器,俗称黑名单,如果发起会话的是黑名单上的IP地址或在某一个网段内,则关闭会话,不再将会话传递下去,非常好理解

/*
*
*/
package org.apache.mina.filter.firewall;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* A {@link IoFilter} which blocks connections from blacklisted remote
* address.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
* @org.apache.xbean.XBean
*/
public class BlacklistFilter extends IoFilterAdapter {
private final List<Subnet> blacklist = new CopyOnWriteArrayList<Subnet>();

private final static Logger LOGGER = LoggerFactory.getLogger(BlacklistFilter.class);
/**
* Sets the addresses to be blacklisted.
*
* NOTE: this call will remove any previously blacklisted addresses.
*
* @param addresses an array of addresses to be blacklisted.
*/
public void setBlacklist(InetAddress[] addresses) {
if (addresses == null) {
throw new IllegalArgumentException("addresses");
}
blacklist.clear();
for (int i = 0; i < addresses.length; i++) {
InetAddress addr = addresses[i];
block(addr);
}
}

/**
* Sets the subnets to be blacklisted.
*
* NOTE: this call will remove any previously blacklisted subnets.
*
* @param subnets an array of subnets to be blacklisted.
*/
public void setSubnetBlacklist(Subnet[] subnets) {
if (subnets == null) {
throw new IllegalArgumentException("Subnets must not be null");
}
blacklist.clear();
for (Subnet subnet : subnets) {
block(subnet);
}
}

/**
* Sets the addresses to be blacklisted.
*
* NOTE: this call will remove any previously blacklisted addresses.
*
* @param addresses a collection of InetAddress objects representing the
*        addresses to be blacklisted.
* @throws IllegalArgumentException if the specified collections contains
*         non-{@link InetAddress} objects.
*/
public void setBlacklist(Iterable<InetAddress> addresses) {
if (addresses == null) {
throw new IllegalArgumentException("addresses");
}

blacklist.clear();

for( InetAddress address : addresses ){
block(address);
}
}

/**
* Sets the subnets to be blacklisted.
*
* NOTE: this call will remove any previously blacklisted subnets.
*
* @param subnets an array of subnets to be blacklisted.
*/
public void setSubnetBlacklist(Iterable<Subnet> subnets) {
if (subnets == null) {
throw new IllegalArgumentException("Subnets must not be null");
}
blacklist.clear();
for (Subnet subnet : subnets) {
block(subnet);
}
}

/**
* Blocks the specified endpoint.
*/
public void block(InetAddress address) {
if (address == null) {
throw new IllegalArgumentException("Adress to block can not be null");
}
//这里的32位表示网络地址为32,也就是一个IP,没有分子网,若是24位(表示一个子网地址),则另外8位为主机号
block(new Subnet(address, 32));
}

/**
* Blocks the specified subnet.
*/
public void block(Subnet subnet) {
if(subnet == null) {
throw new IllegalArgumentException("Subnet can not be null");
}

blacklist.add(subnet);
}

/**
* Unblocks the specified endpoint.
*/
public void unblock(InetAddress address) {
if (address == null) {
throw new IllegalArgumentException("Adress to unblock can not be null");
}

unblock(new Subnet(address, 32));
}

/**
* Unblocks the specified subnet.
*/
public void unblock(Subnet subnet) {
if (subnet == null) {
throw new IllegalArgumentException("Subnet can not be null");
}
blacklist.remove(subnet);
}

@Override
public void sessionCreated(NextFilter nextFilter, IoSession session) {
if (!isBlocked(session)) {
// forward if not blocked
nextFilter.sessionCreated(session);
} else {
blockSession(session);
}
}

@Override
public void sessionOpened(NextFilter nextFilter, IoSession session)
throws Exception {
if (!isBlocked(session)) {
// forward if not blocked
nextFilter.sessionOpened(session);
} else {
blockSession(session);
}
}

@Override
public void sessionClosed(NextFilter nextFilter, IoSession session)
throws Exception {
if (!isBlocked(session)) {
// forward if not blocked
nextFilter.sessionClosed(session);
} else {
blockSession(session);
}
}

@Override
public void sessionIdle(NextFilter nextFilter, IoSession session,
IdleStatus status) throws Exception {
if (!isBlocked(session)) {
// forward if not blocked
nextFilter.sessionIdle(session, status);
} else {
blockSession(session);
}
}

@Override
public void messageReceived(NextFilter nextFilter, IoSession session,
Object message) {
if (!isBlocked(session)) {
// forward if not blocked
nextFilter.messageReceived(session, message);
} else {
blockSession(session);
}
}

@Override
public void messageSent(NextFilter nextFilter, IoSession session,
WriteRequest writeRequest) throws Exception {
if (!isBlocked(session)) {
// forward if not blocked
nextFilter.messageSent(session, writeRequest);
} else {
blockSession(session);
}
}

private void blockSession(IoSession session) {
LOGGER.warn("Remote address in the blacklist; closing.");
session.close(true);
}

private boolean isBlocked(IoSession session) {
SocketAddress remoteAddress = session.getRemoteAddress();
if (remoteAddress instanceof InetSocketAddress) {
InetAddress address = ((InetSocketAddress) remoteAddress).getAddress();

// check all subnets
for(Subnet subnet : blacklist) {
if(subnet.inSubnet(address)) {
return true;
}
}
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: