Skip to content

Instantly share code, notes, and snippets.

@ahhqcheng
Last active December 23, 2015 19:29
Show Gist options
  • Save ahhqcheng/6683359 to your computer and use it in GitHub Desktop.
Save ahhqcheng/6683359 to your computer and use it in GitHub Desktop.
IP转整数以及整数转IP
/**
* 参考:http://aokunsang.iteye.com/blog/622498
* @author chengyongchun
* @since 2013-9-24 <br/>
*/
public class Ipv4Util {
public static Long ip2Long(String ipString){
if(ipString==null){
throw new RuntimeException("ip is null");
}
long result = 0;
StringTokenizer token = new StringTokenizer(ipString,".");
if(token.countTokens()!=4){
throw new RuntimeException("invalid ip: " + ipString);
}
result |= Long.parseLong(token.nextToken())<<24;
result |= Long.parseLong(token.nextToken())<<16;
result |= Long.parseLong(token.nextToken())<<8;
result |= Long.parseLong(token.nextToken());
return result;
}
public static String long2Ip(long ipLong){
StringBuilder sb = new StringBuilder();
sb.append(ipLong>>>24);
sb.append(".");
sb.append(String.valueOf((ipLong>>>16)&0xFF));
sb.append(".");
sb.append(String.valueOf((ipLong>>>8)&0xFF));
sb.append(".");
sb.append(String.valueOf(ipLong&0xFF));
return sb.toString();
}
public static boolean isInnerIp(String ipString) {
Long ip = Ipv4Util.ip2Long(ipString);
Long aBegin = Ipv4Util.ip2Long("10.0.0.0"); // "10.0.0.0"--->10.255.255.255
Long aEnd = Ipv4Util.ip2Long("10.255.255.255");
Long bBegin = Ipv4Util.ip2Long("172.16.0.0"); //"172.16.0.0"--->"172.31.255.255"
Long bEnd = Ipv4Util.ip2Long("172.31.255.255");
Long cBegin = Ipv4Util.ip2Long("192.168.0.0"); // "192.168.0.0"--->"192.168.255.255"
Long cEnd = Ipv4Util.ip2Long("192.168.255.255");
return ((ip >= aBegin && ip <= aEnd) ||
(ip >= bBegin && ip <= bEnd) ||
(ip >= cBegin && ip <= cEnd));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment