Java InetAddress Check isLoopbackIp(InetAddress addr)

Here you can find the source of isLoopbackIp(InetAddress addr)

Description

See if given address is loopback or not

License

Open Source License

Parameter

Parameter Description
addr target address

Return

true : private network

Declaration

public static boolean isLoopbackIp(InetAddress addr) 

Method Source Code


//package com.java2s;
/*// www  .  j  av  a  2s  .  c o m
 License:
    
 blueprint-sdk is licensed under the terms of Eclipse Public License(EPL) v1.0
 (http://www.eclipse.org/legal/epl-v10.html)
    
    
 Distribution:
    
 Repository - https://github.com/lempel/blueprint-sdk.git
 Blog - http://lempel.egloos.com
 */

import java.net.*;

public class Main {
    /**
     * See if given address is loopback or not
     *
     * @param addr target address
     * @return true : private network
     */
    public static boolean isLoopbackIp(InetAddress addr) {
        boolean result = false;

        if (addr instanceof Inet4Address) {
            result = isLoopbackIp((Inet4Address) addr);
        } else if (addr instanceof Inet6Address) {
            result = isLoopbackIp((Inet6Address) addr);
        }

        return result;
    }

    /**
     * See if given address is loopback or not
     *
     * @param addr IPv4 address
     * @return true : private network
     */
    public static boolean isLoopbackIp(Inet4Address addr) {
        boolean result = false;

        byte[] address = addr.getAddress();

        if ((address[0] & 0x000000ff) == 0x7f) {
            // 127.*.*.*
            result = true;
        }

        return result;
    }

    /**
     * See if given address is loopback or not
     *
     * @param addr IPv6 address
     * @return true : private network
     */
    public static boolean isLoopbackIp(Inet6Address addr) {
        boolean result = false;

        byte[] address = addr.getAddress();

        boolean allZero = true;
        for (byte abyte : address) {
            if (abyte != 0) {
                allZero = false;
                break;
            }
        }

        if (allZero && address[address.length - 1] == 1) {
            result = true;
        }

        return result;
    }
}

Related

  1. isLocalAddress(InetAddress address)
  2. isLocalAddress(InetAddress address)
  3. isLocalIP(final InetAddress ip1, final InetAddress ip2, final int mask)
  4. isLocalIpAddress(final InetAddress ipAddress)
  5. isLoopbackAddress(InetAddress address)
  6. isMulticastAddress(InetAddress ipAddr)
  7. isOnNetwork(InetAddress host, InetAddress network, byte[] mask)
  8. isPortFree(int port, InetAddress addr)
  9. isPortInUse(InetAddress address, int port, int count)