当前位置: 代码迷 >> J2SE >> 请教怎么比较IP大小
  详细解决方案

请教怎么比较IP大小

热度:55   发布时间:2016-04-24 02:06:31.0
请问如何比较IP大小
要对入参IP进行查询,数据库下有起始IP和结束IP两个字段,要查询出入参IP在哪条记录的IP范围内。


String inIp = "10.20.160.2";//入参

String startIp = "10.10.160.2";

String endIp = "10.50.160.2";

要查询出inIp是否在startIp和endIp之间,在范围内就就返回startIp和endIp,不在直接跳出了。

------解决方案--------------------
把IP变字符串变为数字(保存IP前字符在数字中高位,应该是网络字节序和机器字节序一种(具体忘记了)),看转入ip的数字是否在ip段中
------解决方案--------------------
下面是我sql2000中的根据ip模糊查询。。。模糊查询应该能匹配到是否在该段。。。

select * from agent as b where subSTRING(left('ip字段',len('ip字段')-1),19,3) like ('192.168.1') 
 
------解决方案--------------------
Java code
public class Demo03{    public static int getValue(String str){    String temp1=str.replace('.',' ');    String[] temp2=temp1.split(" ");      String temp3="";    for(int i=0;i<temp2.length;i++){    temp3+=temp2[i];    }    int temp4=Integer.parseInt(temp3);    return temp4;    }    public static void main(String[] args){    String inIp = "10.20.160.2";    String startIp = "10.10.160.2";    String endIp = "10.50.160.2";    int nInIp=getValue(inIp);    int nstartIp=getValue(startIp);    int nEndIp=getValue(endIp);    if(nEndIp>nInIp&&nInIp>nstartIp){    System.out.println("in");    }else{    System.out.println("not in");    }    }}
------解决方案--------------------
探讨

Java code

public class Demo03
{
public static int getValue(String str){
String temp1=str.replace('.',' ');
String[] temp2=temp1.split(" ");
String temp3="";
for(int i=0;i<temp……

------解决方案--------------------
将IP换成无符号整形,之后直接比较大小就可以了!
例如:String inIp = "10.20.160.2";//入参
换成整形为 10 * 256 * 256 * 256 + 20 * 256 * 256 + 160 * 256 + 2 = 18784258
之后。。。。比较就可以确定范围了吧!
  相关解决方案