All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.eBus.config.InetAddressComparator Maven / Gradle / Ivy

//
// Copyright 2009 Charles W. Rapp
//
// 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.
//

package net.sf.eBus.config;

import java.io.Serializable;
import java.net.InetAddress;
import java.util.Comparator;

/**
 * Compares two {@code InetAddress} addresses using the address
 * bytes.
 *
 * @author Charles Rapp
 */

public class InetAddressComparator
    implements Comparator,
               Serializable
{
//--------------------------------------------------------------
// Member data.
//

    //-----------------------------------------------------------
    // Constants.
    //

    /**
     * Java serialization identifier.
     */
    private static final long serialVersionUID = 0x050200L;

//--------------------------------------------------------------
// Member methods.
//

    //----------------------------------------------------------
    // Comparator Interface Implementation.
    //

    /**
     * Returns an integer <, equal to or > zero if
     * {@code a1} is <, equal to or > {@code a2}. The
     * comparison is based on the raw IP address octets. If
     * {@code a1} has fewer bytes or more bytes than {@code a2},
     * then a negative or positve integer is returned,
     * respectively. Otherwise, the IP address octets are
     * compared until the first non-zero result is found.
     * @param a1 First compared address.
     * @param a2 Second compared address.
     * @return an integer <, equal to or > zero if
     * {@code a1} is <, equal to or > {@code a2}.
     */
    @Override
    public int compare(final InetAddress a1,
                       final InetAddress a2)
    {
        final byte[] b1 = a1.getAddress();
        final byte[] b2 = a2.getAddress();
        int index;
        final int size =
            (b1.length < b2.length ? b1.length : b2.length);
        int retval = (b1.length - b2.length);

        for (index = 0; index < size && retval == 0; ++index)
        {
            retval = (b1[index] - b2[index]);
        }

        return (retval);
    } // end of compare(InetAddress, InetAddress)

    //
    // end of Comparator Interface Implementation.
    //----------------------------------------------------------
} // end of class InetAddressComparator




© 2015 - 2025 Weber Informatics LLC | Privacy Policy