Java InetAddress inetAddressesComparator(final boolean sameHost)

Here you can find the source of inetAddressesComparator(final boolean sameHost)

Description

Returns comparator that sorts remote node addresses.

License

Open Source License

Parameter

Parameter Description
sameHost True if remote node resides on the same host, false otherwise.

Return

Comparator.

Declaration

public static Comparator<InetSocketAddress> inetAddressesComparator(final boolean sameHost) 

Method Source Code

//package com.java2s;
/* /*from w w w .  j a va2  s .  co  m*/
 Copyright (C) GridGain Systems. All Rights Reserved.
     
 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.*;

import java.util.*;

public class Main {
    /**
     * Returns comparator that sorts remote node addresses. If remote node resides on the same host, then put
     * loopback addresses first, last otherwise.
     *
     * @param sameHost {@code True} if remote node resides on the same host, {@code false} otherwise.
     * @return Comparator.
     */
    public static Comparator<InetSocketAddress> inetAddressesComparator(final boolean sameHost) {
        return new Comparator<InetSocketAddress>() {
            @Override
            public int compare(InetSocketAddress addr1, InetSocketAddress addr2) {
                if (addr1.isUnresolved() && addr2.isUnresolved())
                    return 0;

                if (addr1.isUnresolved() || addr2.isUnresolved())
                    return addr1.isUnresolved() ? 1 : -1;

                boolean addr1Loopback = addr1.getAddress().isLoopbackAddress();

                // No need to reorder.
                if (addr1Loopback == addr2.getAddress().isLoopbackAddress())
                    return 0;

                if (sameHost)
                    return addr1Loopback ? -1 : 1;
                else
                    return addr1Loopback ? 1 : -1;
            }
        };
    }
}

Related

  1. greaterThan(InetAddress inetAddress1, InetAddress inetAddress2)
  2. hasIp(InetAddress ip)
  3. hasLocalScope(InetAddress addr)
  4. increment(InetAddress address)
  5. inetAddressCompare(final InetAddress address1, final InetAddress address2)
  6. inetAddressesCompare(final InetAddress[] addresses1, final InetAddress[] addresses2)
  7. inetAddressFromThriftString(String ipAddress)
  8. inetAddressGt(InetAddress a, InetAddress b)
  9. inetAddrToByteArray(InetAddress a)