1.ip转char
下列程序有两个实用功能:
1.ip转32位char []
2.给一个ip和一对<ip,掩码>,判断是否命中。
class WhiteIpMask {
public static Set set = new HashSet<>();
public String ip;
public int mask;
public WhiteIpMask(String ip, int mask) {
this.ip = ip;
this.mask = mask;
}
static boolean add(WhiteIpMask e) {
return set.add(e);
}
public static boolean isInWhiteList(String ip) {
for (WhiteIpMask e : set)
if (isInWhiteList(e, ip))
return true;
return false;
}
static boolean isInWhiteList(WhiteIpMask e, String ip) {
char[] whiteIpArr = strToCharArr(e.ip);
int mask = e.mask;
char[] ipArr = strToCharArr(ip);
for (int i = 0; i < mask; i++)
if (whiteIpArr[i] != ipArr[i])
return false;
return true;
}
/**
* @param x
* 3
* @return 00000011
*/
public static String intTo8BitBin(int x) {
String str = Integer.toBinaryString(x);
char zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' };
return new String(zero, 0, 8 - str.length()) + str;
}
/**
* @param ipStr
* 1.2.3.4
* @return 00000001 00000010 00000011 00000100
*/
public static char[] strToCharArr(String ipStr) {
String strArr[] = ipStr.split("\\.");
int a = Integer.valueOf(strArr[0]);
int b = Integer.valueOf(strArr[1]);
int c = Integer.valueOf(strArr[2]);
int d = Integer.valueOf(strArr[3]);
return (intTo8BitBin(a) + intTo8BitBin(b) + intTo8BitBin(c) + intTo8BitBin(d))
.toCharArray();
}
}
2.ip转long
long ipv4ToLong(String ip) {
String[] parts = ip.split("\\.");
return (Long.parseLong(parts[0]) << 24) | (Long.parseLong(parts[1]) << 16) | (Long.parseLong(parts[2]) << 8) | (Long.parseLong(parts[3]))
}