Java InetAddress compareInetAddresses(InetAddress a1, InetAddress a2)

Here you can find the source of compareInetAddresses(InetAddress a1, InetAddress a2)

Description

compare Inet Addresses

License

Open Source License

Declaration

public static int compareInetAddresses(InetAddress a1, InetAddress a2) 

Method Source Code

//package com.java2s;
/**/*from   w ww .  j a v  a  2s.co  m*/
 * NetXMS - open source network management system
 * Copyright (C) 2003-2015 Victor Kirhenshtein
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;

public class Main {
    public static int compareInetAddresses(InetAddress a1, InetAddress a2) {
        if (a1 == null)
            return (a2 == null) ? 0 : -1;

        if (a2 == null)
            return 1;

        if ((a1 instanceof Inet4Address) && (a2 instanceof Inet6Address))
            return -1;

        if ((a1 instanceof Inet6Address) && (a2 instanceof Inet4Address))
            return 1;

        byte[] b1 = a1.getAddress();
        byte[] b2 = a2.getAddress();
        int length = Math.min(b1.length, b2.length);
        for (int i = 0; i < length; i++) {
            int n1 = (int) b1[i] & 0xFF;
            int n2 = (int) b2[i] & 0xFF;
            if (n1 < n2)
                return -1;
            if (n1 > n2)
                return 1;
        }
        return b1.length - b2.length;
    }
}

Related

  1. canonicalIpAddress(InetAddress addr)
  2. checkConnection(InetAddress address, int port, int timeout)
  3. compareAddresses(InetAddress one, InetAddress two)
  4. compareInetAddresses(InetAddress a, InetAddress b)
  5. CompareIP(InetAddress ip1, InetAddress ip2)
  6. contains(InetAddress network, InetAddress netmask, InetAddress ip)
  7. convertInetAddressToLong(InetAddress addr)
  8. convertInetAddressToLong(InetAddress address)