Java InetAddress canonicalIpAddress(InetAddress addr)

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

Description

Converts the IP address to a canonical string which allows correct comparison behavior with IP address (used for sorting and range queries).

License

Open Source License

Parameter

Parameter Description
addr IP address.

Return

The canonical format used for sorting and range queries.

Declaration

public static String canonicalIpAddress(InetAddress addr) 

Method Source Code

//package com.java2s;
/*****************************************************************************
 * //from   ww w . jav  a 2  s .  c  om
 * Copyright (C) Zenoss, Inc. 2011, all rights reserved.
 * 
 * This content is made available according to terms specified in
 * License.zenoss under the directory where your Zenoss product is installed.
 * 
 ****************************************************************************/

import java.net.InetAddress;

public class Main {
    /**
     * Converts the IP address to a canonical string which allows correct comparison
     * behavior with IP address (used for sorting and range queries). IPv4 and IPv6 
     * addresses are converted to have leading zeros in addresses (i.e. 192.168.1.2 becomes
     * 192.168.001.002 and ::1 becomes 0000:0000:0000:0000:0000:0000:0000:0001).
     * 
     * @param addr IP address.
     * @return The canonical format used for sorting and range queries.
     */
    public static String canonicalIpAddress(InetAddress addr) {
        StringBuilder sb = new StringBuilder(36);
        byte[] addrbytes = addr.getAddress();
        if (addrbytes.length == 4) {
            for (byte b : addrbytes) {
                int i = (b & 0xff);
                if (sb.length() > 0) {
                    sb.append('.');
                }
                sb.append(String.format("%03d", i));
            }
        } else if (addrbytes.length == 16) {
            for (int i = 0; i < addrbytes.length; i++) {
                int octet = (addrbytes[i] & 0xff);
                if (sb.length() > 0 && (i % 2) == 0) {
                    sb.append(':');
                }
                sb.append(String.format("%02x", octet));
            }
        } else {
            throw new IllegalStateException("Unexpected InetAddress storage");
        }
        return sb.toString();
    }
}

Related

  1. checkConnection(InetAddress address, int port, int timeout)
  2. compareAddresses(InetAddress one, InetAddress two)
  3. compareInetAddresses(InetAddress a, InetAddress b)
  4. compareInetAddresses(InetAddress a1, InetAddress a2)