2017-02-20 105 views
0

我如何在Java中IPRange分拣机在Java中

的ipranges为实例进行排序:

我输入IpRange一串地址即

9.9.9.9/12 
100.0.0.0/12 
8.8.8.8/12 
1.2.3.4/32 
1.2.2.2/12 
12.3.1.45/12 

我的输出应该

1.2.2.2/12 
1.2.3.4/32 
8.8.8.8/12 
9.9.9.9/12 
12.3.1.45/12 
100.0.0.0/12 

TIA

回答

-1

您可以编写自己的比较器。看起来是一件容易的事。这也在blogs之一中共享。以下是相同的执行情况(仅供参考),

public class TestIPSorter { 
    @Test 
    public void test() { 
     String[] input = {"9.9.9.9/12" ,"100.0.0.0/12" ,"8.8.8.8/12" ,"1.2.3.4/32" ,"1.2.2.2/12", "12.3.1.45/12"}; 
     String[] expectedOutput = {"1.2.2.2/12" ,"1.2.3.4/32", "8.8.8.8/12" ,"9.9.9.9/12" ,"12.3.1.45/12", "100.0.0.0/12"}; 


     String[] sortedIp = IPSorter.sort(input); 

     Assert.assertArrayEquals(expectedOutput, sortedIp); 
    } 
} 


public class IPSorter { 

    public static String[] sort(String[] input) { 
     IpAddress[] array = Arrays.stream(input).map(i -> IpAddress.valueOf(i)).toArray(IpAddress[]::new); 
     Arrays.sort(array); 
     return Arrays.stream(array).map(ipAd -> ipAd.getAddress()).toArray(String[]::new); 
    } 

    private static class IpAddress implements Comparable<IpAddress> { 

     private final String original; 
     private final String ipStart; 
     private final int to; 

     private IpAddress(String address) { 
      int forwardSlash = address.lastIndexOf("/"); 
      ipStart = address.substring(0, forwardSlash); 
      to = Integer.parseInt(address.substring(forwardSlash + 1)); 
      original = address; 
     } 

     static IpAddress valueOf(String address) { 
      return new IpAddress(address); 
     } 

     String getAddress() { 
      return original; 
     } 

     @Override 
     public int compareTo(IpAddress o) { 
      try { 
       byte[] ba1 = InetAddress.getByName(this.ipStart).getAddress(); 
       byte[] ba2 = InetAddress.getByName(o.ipStart).getAddress(); 

       // general ordering: ipv4 before ipv6 
       if (ba1.length < ba2.length) 
        return -1; 
       if (ba1.length > ba2.length) 
        return 1; 

       // we have 2 ips of the same type, so we have to compare each byte 
       for (int i = 0; i < ba1.length; i++) { 
        int b1 = unsignedByteToInt(ba1[i]); 
        int b2 = unsignedByteToInt(ba2[i]); 
        if (b1 == b2) 
         continue; 
        if (b1 < b2) { 
         return -1; 
        } else { 
         return 1; 
        } 
       } 
       return compareRange(to, o.to); 
      } catch (UnknownHostException e) { 
       throw new RuntimeException(e); 
      } 
     } 

     private int compareRange(int range1, int range2) { 
      return Integer.compare(range1, range2); 


     } 

     private int unsignedByteToInt(byte b) { 
      return (int) b & 0xFF; 
     } 
    } 


} 
+0

请问downvoter请解释什么是错误的答案? – GauravJ

+0

我不是downvoter,但你的回答更像是评论 – haifzhan

+0

@HaifengZhang,我也添加了代码片段。 – GauravJ