Java InetAddress CompareIP(InetAddress ip1, InetAddress ip2)

Here you can find the source of CompareIP(InetAddress ip1, InetAddress ip2)

Description

Compares the two IP Addresses.

License

Apache License

Parameter

Parameter Description
ip1 a parameter

Declaration

public static int CompareIP(InetAddress ip1, InetAddress ip2) 

Method Source Code

//package com.java2s;
/*//  w ww .j  a v a 2 s  . c  o m
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.net.InetAddress;

public class Main {
    /**
     * Compares the two IP Addresses. Returns 0 if both are equal, 1 if ip1 is greateer than ip2 otherwise -1.
     *
     * @param ip1
     * @param ip1
     * @return
     */
    public static int CompareIP(InetAddress ip1, InetAddress ip2) {

        int ipval1, ipval2;
        ipval1 = IPAddressToLong(ip1);
        ipval2 = IPAddressToLong(ip2);

        if (ipval1 == ipval2) {
            return 0;
        }
        if (ipval1 > ipval2) {
            return 1;
        } else {
            return -1;
        }
    }

    private static int IPAddressToLong(InetAddress IPAddr) {

        byte[] byteIP = IPAddr.getAddress();

        int ip = (int) byteIP[0] << 24;

        ip += (int) byteIP[1] << 16;

        ip += (int) byteIP[2] << 8;

        ip += (int) byteIP[3];

        return ip;
    }
}

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. compareInetAddresses(InetAddress a1, InetAddress a2)
  6. contains(InetAddress network, InetAddress netmask, InetAddress ip)
  7. convertInetAddressToLong(InetAddress addr)
  8. convertInetAddressToLong(InetAddress address)
  9. convertLongToInetAddress(long address)