IP地址划分为 A,B,C,D,E五类
A类地址1.0.0.0~126.255.255.255;
B类地址128.0.0.0~191.255.255.255;
C类地址192.0.0.0~223.255.255.255;
D类地址224.0.0.0~239.255.255.255;
E类地址240.0.0.0~255.255.255.255
私网IP范围是:
10.0.0.0~10.255.255.255
172.16.0.0~172.31.255.255
192.168.0.0~192.168.255.255
// 1代表A类,2代表B类,3代表C类;4代表其它类型
public final static int IP_A_TYPE = 1;
public final static int IP_B_TYPE = 2;
public final static int IP_C_TYPE = 3;
public final static int IP_OTHER_TYPE = 4;
// A类地址范围:1.0.0.1---126.255.255.254
private static int[] IpATypeRange;
// B类地址范围:128.0.0.1---191.255.255.254
private static int[] IpBTypeRange;
// C类地址范围:192.168.0.0~192.168.255.255
private static int[] IpCTypeRange;
// A,B,C类地址的默认mask
private static int DefaultIpAMask;
private static int DefaultIpBMask;
private static int DefaultIpCMask;
// 初始化
static {
IpATypeRange = new int[2];
IpATypeRange[0] = getIpV4Value("1.0.0.1");
IpATypeRange[1] = getIpV4Value("126.255.255.254");
IpBTypeRange = new int[2];
IpBTypeRange[0] = getIpV4Value("128.0.0.1");
IpBTypeRange[1] = getIpV4Value("191.255.255.254");
IpCTypeRange = new int[2];
IpCTypeRange[0] = getIpV4Value("192.168.0.0");
IpCTypeRange[1] = getIpV4Value("192.168.255.255");
DefaultIpAMask = getIpV4Value("255.0.0.0");
DefaultIpBMask = getIpV4Value("255.255.0.0");
DefaultIpCMask = getIpV4Value("255.255.255.0");
}
public static int getIpV4Value(String ipOrMask) {
byte[] addr = getIpV4Bytes(ipOrMask);
int address1 = addr[3] & 0xFF;
address1 |= ((addr[2] << 8) & 0xFF00);
address1 |= ((addr[1] << 16) & 0xFF0000);
address1 |= ((addr[0] << 24) & 0xFF000000);
return address1;
}
public static byte[] getIpV4Bytes(String ipOrMask) {
try {
String[] addrs = ipOrMask.split("\\.");
int length = addrs.length;
byte[] addr = new byte[length];
for (int index = 0; index < length; index++) {
addr[index] = (byte) (Integer.parseInt(addrs[index]) & 0xff);
}
return addr;
} catch (Exception e) {
}
return new byte[4];
}
/**
* 检测ipV4 的类型,包括A类,B类,C类,其它(C,D和广播)类等
*
* @param ipV4
* @return 返回1代表A类,返回2代表B类,返回3代表C类;返回4代表D类
*/
public static int checkIpV4Type(String ipV4) {
int inValue = getIpV4Value(ipV4);
if (inValue >= IpCTypeRange[0] && inValue <= IpCTypeRange[1]) {
return IP_C_TYPE;
} else if (inValue >= IpBTypeRange[0] && inValue <= IpBTypeRange[1]) {
return IP_B_TYPE;
} else if (inValue >= IpATypeRange[0] && inValue <= IpATypeRange[1]) {
return IP_A_TYPE;
}
return IP_OTHER_TYPE;
}
public static void main(String[] args) {
System.out.println(checkIpV4Type("191.255.255.254"));//输出2 对应是B类地址
}
|