title: Sorting IP addresses in Java
body: <p>I have read on this site inlcuding: <a href="https://stackoverflow.com/questions/5894818/how-to-sort-arraylistlong-in-java-in-decreasing-order">link1</a> and <a href="https://stackoverflow.com/questions/1694751/java-array-sort-descending">link2</a> amongst others how to sort IP addresses (String representation of them) in Java. However I am not getting the correct output.</p>
  
  <p>My Data (an example):</p>
  
  <p>::2:3:4:5:6:7 </p>
  
  <p>::2:3:4:5:6:7:8</p>
  
  <p>1::8</p>
  
  <p>1::2:3</p>
  
  <p>1::2:3:4</p>
  
  <p>1::5:256.2.3.4</p>
  
  <p>1::3000.30.30.30</p>
  
  <p>fe80::217:f2ff:254.7.237.98,1:2:3:4::5:1.2.3.4</p>
  
  <p>2001:0000:1234:0000:0000:C1C0:ABCD:0876</p>
  
  <p>I am adding these IP addresses (some valid some invalid) to an ArrayList and then passing it to this below:</p>
  
  <pre><code>ArrayList &lt;String&gt; list = new ArrayList&lt;String&gt;();
  
  String [] tests = {"::2:3:4:5:6:7","2:3:4:5:6:7","::5:3:4:5:6:7:8","::5:3:4:5:6:7:8:9:0","1::8","1::2:3","1::2:3:4","1::5:256.2.3.4","1:1:3000.30.30.30","ae80::217:f2ff:254.7.237.98,1:2:3:4::5:1.2.3.4","2001:0000:1234:0000:0000:C1C0:ABCD:0876",
       "12345::6:7:8","1::1.2.900.4","fe80::","::ffff:0:0"};
  </code></pre>
  
  <p>//Add to ArrayList</p>
  
  <pre><code>    for (String test1 : tests) {
      list.add(test1);
      }
  </code></pre>
  
  <p>//Compare and sort</p>
  
  <pre><code> Collections.sort(list);
      Collections.reverse(list);
  
      //Collections.sort(ipList, new Comparator&lt;String&gt;() {
      for(String ip: list){
      System.out.println(ip);
  }
  </code></pre>
  
  <p>However I am not able to correctly sort the data and get incorrectly sorted results in <strong>DESCENDING ORDER</strong>. Can anyone guide me to a better way ? Thanks in advance. Please remember in ip addresses between "::" there is a zero so this is equivalent to 0:0:0</p>
  
  <p>The result I get is:</p>
  
  <p>fe80::</p>
  
  <p>ae80::217:f2ff:254.7.237.98,1:2:3:4::5:1.2.3.4</p>
  
  <p>::ffff:0:0</p>
  
  <p>::5:3:4:5:6:7:8:9:0</p>
  
  <p>::5:3:4:5:6:7:8</p>
  
  <p>::2:3:4:5:6:7</p>
  
  <p>2:3:4:5:6:7</p>
  
  <p>2001:0000:1234:0000:0000:C1C0:ABCD:0876</p>
  
  <p>1::8</p>
  
  <p>1::5:256.2.3.4</p>
  
  <p>1::2:3:4</p>
  
  <p>1::2:3</p>
  
  <p>1::1.2.900.4</p>
  
  <p>1:1:3000.30.30.30</p>
  
  <p>12345::6:7:8</p>