Java InetAddress compareInetAddresses(InetAddress a, InetAddress b)

Here you can find the source of compareInetAddresses(InetAddress a, InetAddress b)

Description

compare Inet Addresses

License

Open Source License

Declaration

public static int compareInetAddresses(InetAddress a, InetAddress b) 

Method Source Code


//package com.java2s;
/*/*  w ww  . ja va  2  s  .c o m*/
 * Copyright (c) 2014 Contextream, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

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

public class Main {
    public static int compareInetAddresses(InetAddress a, InetAddress b) {
        int i;
        if (a instanceof Inet4Address && b instanceof Inet6Address) {
            return -1;
        } else if (a instanceof Inet6Address && b instanceof Inet4Address) {
            return 1;
        } else if (a instanceof Inet4Address && b instanceof Inet4Address) {
            byte[] aBytes = ((Inet4Address) a).getAddress();
            byte[] bBytes = ((Inet4Address) b).getAddress();
            for (i = 0; i < 4; i++) {
                if (aBytes[i] < bBytes[i]) {
                    return -1;
                } else if (aBytes[i] > bBytes[i]) {
                    return 1;
                }
            }
            return 0;
        } else if (a instanceof Inet6Address && b instanceof Inet6Address) {
            byte[] aBytes = ((Inet6Address) a).getAddress();
            byte[] bBytes = ((Inet6Address) b).getAddress();
            for (i = 0; i < 16; i++) {
                if (aBytes[i] < bBytes[i]) {
                    return -1;
                } else if (aBytes[i] > bBytes[i]) {
                    return 1;
                }
            }
            return 0;
        }
        return 0;
    }
}

Related

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