Here you can find the source of convertIpv4ToIpv6(String ip)
Parameter | Description |
---|---|
ip | The Ipv4 address to convert |
public static final String convertIpv4ToIpv6(String ip)
//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; } }