如何确定IP的范围

pumanchawulaowu 2010-04-22 11:00:25
DB内有如下记录:
beginip endip province
192.168.000.000 192.168.001.255 ce
192.168.002.000 192.168.002.255 bj
。。。。。。

那么我怎么确定192.168.002.121 是在bj呢?
...全文
56 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
欢乐极客 2010-04-23
  • 打赏
  • 举报
回复
有问题联系代码里面的qq
没问题则结贴
欢乐极客 2010-04-23
  • 打赏
  • 举报
回复
解析和判断


package com.xiaoyong;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
* @author 屈小勇 QQ:306741422
*
*/
public class ConfirmIp {

private Map<IpObject, String> map;

public ConfirmIp() {
map = new HashMap<IpObject, String>();
}

// 添加记录
public void addRecord(String beginIp, String endIp, String province) {
IpObject ipObject = new IpObject(beginIp, endIp);
map.put(ipObject, province);
}

public void confirmIpLocation(String ip) {
Iterator<IpObject> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
IpObject ipObject = iterator.next();
String beginIp = ipObject.getBeginIp();
// 如果前面三组数字匹配
if (ip.substring(0, 11).equals(beginIp.substring(0, 11))) {
int ipEnd = Integer.parseInt(ip.substring(12));
int beginIpEnd = Integer.parseInt(beginIp.substring(12));
if (ipEnd >= beginIpEnd) {
String province = this.map.get(ipObject);
System.out.println(ip + "所在的province为:" + province);
return;
}
}
}
System.out.println("没有找到 " + ip + " 所在的位置");
}

// 使用内部类封装IP段
class IpObject extends Object {

private String beginIp;

private String endIp;

public IpObject(String beginIp, String endIp) {
this.beginIp = beginIp;
this.endIp = endIp;
}

public String getBeginIp() {
return beginIp;
}

public String getEndIp() {
return endIp;
}
}

public static void main(String[] args) {
ConfirmIp confirmIp = new ConfirmIp();
confirmIp.addRecord("192.168.000.000", "192.168.001.255", "ce");
confirmIp.addRecord("192.168.002.000", "192.168.002.255", "bj");
confirmIp.confirmIpLocation("192.168.002.121");
}
}

pumanchawulaowu 2010-04-23
  • 打赏
  • 举报
回复
嗯~
如果是192.168.2.121呢,楼上提供的方法不太兼容噢?
rthfdh 2010-04-23
  • 打赏
  • 举报
回复
这个问题太简单了,直接用字符比较

if( your_string.compare(min) >=0 && your_string.compare(max)<=0)

min,max为最小、最大值界限
susuifeng 2010-04-23
  • 打赏
  • 举报
回复
帮顶..........

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧