Java IP Address Convert To convertIpv4ToIpv6(String ip)

Here you can find the source of convertIpv4ToIpv6(String ip)

Description

convert Ipv To Ipv

License

Open Source License

Parameter

Parameter Description
ip The Ipv4 address to convert

Return

The converted address in Ipv6, or the original ip if the conversion failed.

Declaration

public static final String convertIpv4ToIpv6(String ip) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /** @param ip The Ipv4 address to convert
     * @return The converted address in Ipv6, or the original ip if the
     *         conversion failed. */
    public static final String convertIpv4ToIpv6(String ip) {
        if (ip == null || ip.isEmpty()) {
            return ip;
        }//from w  w  w . j ava2s  .c  om
        String port = "";
        if (ip.contains(":")) {
            port = ip.substring(ip.indexOf(":"));
            ip = ip.substring(0, ip.indexOf(":"));
        }
        String[] octets = ip.split("\\.");
        if (octets.length == 4) {
            if (octets[0].contains("/")) {
                octets[0] = octets[0].substring(octets[0].indexOf("/"));
            }
            final String s1 = Integer.toHexString(Integer.parseInt(octets[0]))
                    + convertIntToHex(Integer.parseInt(octets[1]));
            final String s2 = Integer.toHexString(Integer.parseInt(octets[2]))
                    + convertIntToHex(Integer.parseInt(octets[3]));
            return "[::ffff:" + (s1.startsWith("00") ? s1.substring(2) : s1) + ":"
                    + (s2.startsWith("00") ? s2.substring(2) : s2) + "]" + port;
        }
        return ip;
    }

    public static final String convertIntToHex(int i) {
        String rtrn = Integer.toHexString(i);
        return rtrn.length() == 1 ? "0" + rtrn : rtrn;
    }
}

Related

  1. convertIPAdressToBytes(String ip)
  2. convertIpPortToUniqueId(byte[] quad, int port)
  3. convertIpv4Address(String ip)
  4. convertIpv4AddressToString(byte[] ipv4Address)
  5. convertIPv4NetworkPrefixLength(short length)
  6. convertIpv6Address(String ip)
  7. convertIPV6Host(String host)