tags:

views:

3037

answers:

4

Is this possible? How can you convert an ipv4 to an ipv6 address?

a few example from here:

0.0.0.0   -> ::
127.0.0.1 -> ::1

I'm searching a solution in Java.

Thanks,

+16  A: 

There is no IPv4 to IPv6 mapping that is meaningful. things like 0.0.0.0 and 127.0.0.1 are special cases in the spec, so they have equivalent meaning. But given an IPv4 address it tells you nothing about what its specific IPv6 address would be. You can use a DNS lookup to see if a given IP address resolves to a host which in turn resolves to an IPv6 address in addition to an IPv4 address, but the DNS server would have to be configured to support that for the specific machine.

Yishai
A: 

Will this do?

    final InetAddress ipv4 = InetAddress.getByName( "127.0.0.1" );

    final InetAddress ipv6 =
        InetAddress.getByName( "::" + ipv4.getHostAddress( ) );

    System.out.println( ipv6 );
Alexander Pogrebnyak
This will not actually convert the address from IP4 to IP6 or vice versa.
Molex
+2  A: 

There used to be a reserved address space in IPv6 for IPv4 addresses, where you simply prefixed the IPv4 address with 96 0-bits. E.g. 192.168.10.13 -> ::C0A8:0A0D. As I know this has been deprecated, and there's no direct conversion available anymore.

Zed
I think there are still IPv4-mapped IPv6 addresses which were not deprecated. Your example in this scheme would be ::ffff:c0a8:0a0d. The one with 0s in it was called IPv4-compatible IPv6 addresses.
Tony van der Peet
A: 

Hybrid dual-stack IPv6/IPv4 implementations typically support a special class of addresses, the IPv4-mapped addresses. For more check following link:

http://en.wikipedia.org/wiki/IPv6#IPv4-mapped_addresses

for converting ipv4 to mapped ipV6 u can use following:

String ip = "127.0.0.1"; 
String[] octets = ip.split("\\.");
byte[] octetBytes = new byte[4];
 for (int i = 0; i < 4; ++i) {
                    octetBytes[i] = (byte) Integer.parseInt(octets[i]);
}

byte ipv4asIpV6addr[] = new byte[16];
ipv4asIpV6addr[10] = (byte)0xff;
ipv4asIpV6addr[11] = (byte)0xff;
ipv4asIpV6addr[12] = octetBytes[0];
ipv4asIpV6addr[13] = octetBytes[1];
ipv4asIpV6addr[14] = octetBytes[2];
ipv4asIpV6addr[15] = octetBytes[3];
Deep