通过C#和Java实现对IP是否存在某网段的判断
内容提示:在多服务器资源网站的项目中,经常需要自动根据用户的IP选择最优先的服务器资源进行特定的指向服务,这就需要对客户IP是否存在网段的判断技术,下面整理两个版本的例子,供大家参考。
[C#.net版]如何判断某一个IP是否在一个IP段里边
/// <summary>
/// 分割IP
/// </summary>
/// <param name="ipAddress">IP地址</param>
/// <returns></returns>
private long getIpNum(String ipAddress)
{
String[] ip = ipAddress.Split(new char[] { '.' });
long a = int.Parse(ip[0]);
long b = int.Parse(ip[1]);
long c = int.Parse(ip[2]);
long d = int.Parse(ip[3]);
return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
}
/// 判断客户端的IP是否在某个ip段中
/// <param name="clientIp">客户端的IP</param>
/// <param name="begin">开始IP</param>
/// <param name="end">结束IP</param>
/// <returns></returns>
private bool isInner(long clientIp, long begin, long end)
{
return (clientIp >= begin) && (clientIp <= end);
}
///调用方法
long ip = getIpNum("59.162.200.35");
long start_ip = getIpNum("59.162.200.0");
long end_ip = getIpNum("59.162.201.255");
if (isInner(ip, start_ip, end_ip))
{
Response.Write("是");
}
else
{
Response.Write("不是");
}
[Java版]判断一个IP是否在指定网段中
/**
* 判断ip是否在指定网段中
* @author dh
* @param iparea
* @param ip
* @return boolean
*/
public static boolean ipIsInNet(String iparea, String ip) {
if (iparea == null)
throw new NullPointerException("IP段不能为空!");
if (ip == null)
throw new NullPointerException("IP不能为空!");
iparea = iparea.trim();
ip = ip.trim();
final String REGX_IP = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
final String REGX_IPB = REGX_IP + "\\-" + REGX_IP;
if (!iparea.matches(REGX_IPB) || !ip.matches(REGX_IP))
return false;
int idx = iparea.indexOf('-');
String[] sips = iparea.substring(0, idx).split("\\.");
String[] sipe = iparea.substring(idx + 1).split("\\.");
String[] sipt = ip.split("\\.");
long ips = 0L, ipe = 0L, ipt = 0L;
for (int i = 0; i < 4; ++i) {
ips = ips << 8 | Integer.parseInt(sips[i]);
ipe = ipe << 8 | Integer.parseInt(sipe[i]);
ipt = ipt << 8 | Integer.parseInt(sipt[i]);
}
if (ips > ipe) {
long t = ips;
ips = ipe;
ipe = t;
}
return ips <= ipt && ipt <= ipe;
}