java获取ipv4网络地址类型
记录下ipv4的地址分类,主要看前8位的前几位,也就是第一个点前的三个数字,转换为二进制,
从左至右,观察得出网络地址类型
类型 | 前几位 |
---|---|
A | 0 |
B | 10 |
D | 110 |
E | 1110 |
B | 1111 |
测试类
package test;
import org.junit.Test;
import util.BinaryUtil;
public class IPClassifyTest {
@Test
public void test() {
System.out.println(classify("239.255.255.255"));
}
IPClassification classify(String ip) {
//验证ip是否合法
check(ip);
String[] strs = ip.split("\\.");
int a=Integer.parseInt(strs[0]);
for(IPClassification classification:IPClassification.values())
{
int length=classification.getPrefix().length();
if(Integer.parseInt(classification.getPrefix(), 2)==BinaryUtil.getIndex(a, 8, length)) {
return classification;
}
}
return null;
}
public void check(String ip) {
if(ip==null) {
throw new NullPointerException("ip为空");
}
String[] strs=ip.split("\\.");
if(strs.length!=4) {
throw new RuntimeException("不是ipv4协议");
}
for(String str:strs) {
int a=Integer.parseInt(str);
if(a>255||a<0) {
throw new RuntimeException("不是ipv4协议");
}
}
}
enum IPClassification {
A("0"), B("10"), C("110"), D("1110"),E("1111");
private String prefix;
IPClassification(String prefix) {
this.prefix=prefix;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
}
二进制工具类
package util;
public class BinaryUtil {
/**
* 模2除法运算
* @return int 余数
* 改为e返回商
* */
public static int m2Div(int a,int b) {
int lengtha=intLength(a,2);
int lengthb=intLength(b,2);
//存储余数
int d=0;
//存储商
int e=0;
for(int i=lengtha;i>0;i--) {
int c=getIndex(a,i);
d=(d<<1)+c;
e=e<<1;
if(intLength(d, 2)==lengthb) {
e=e+1;
d=d^b;
}
}
return d;
}
public static int intLength(int num,int radix) {
for(int i=0;i<32;i++) {
int c=(int) Math.pow(radix, i);
if(num%c==num) {
return i;
}
}
return 0;
}
public static int getIndex(int a,int index) {
return getIndex(a,index,1);
}
public static int getIndex(int a,int index,int length) {
if(index<length) {
throw new RuntimeException("起始位置小于长度");
}
return a>>(index-length)&((1<<length)-1);
}
}