Repository: TheAlgorithms/Java
Pull request #5783 (2024-10-13 15:01:30)

feat: Add `IPv6Converter` new algorithm with Junit tests
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5783?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `68.00000%` with `8 lines` in your changes missing coverage. Please review.
> Project coverage is 64.14%. Comparing base [(`9b52ac9`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/9b52ac9633c5f58087c2ad7ac8af4a44009cea2b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`f6a79a6`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/f6a79a63506eaf381d934a535b15128aaf0022c5?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5783?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...a/com/thealgorithms/conversions/IPv6Converter.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5783?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fconversions%2FIPv6Converter.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9jb252ZXJzaW9ucy9JUHY2Q29udmVydGVyLmphdmE=) | 68.00% | [4 Missing and 4 partials :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5783?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5783      +/-   ##
============================================
- Coverage     64.14%   64.14%   -0.01%     
- Complexity     4205     4212       +7     
============================================
  Files           587      588       +1     
  Lines         16390    16415      +25     
  Branches       3163     3169       +6     
============================================
+ Hits          10513    10529      +16     
- Misses         5448     5453       +5     
- Partials        429      433       +4     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5783?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

Hardvan: I have fixed the PR checks.

Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index fa9c2653..31f46916 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -100,6 +100,7 @@
             * [IntegerToEnglish](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java)
             * [IntegerToRoman](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java)
             * [IPConverter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IPConverter.java)
+            * [IPv6Converter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IPv6Converter.java)
             * [MorseCodeConverter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java)
             * [OctalToBinary](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToBinary.java)
             * [OctalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java)
@@ -784,6 +785,7 @@
             * [IntegerToEnglishTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IntegerToEnglishTest.java)
             * [IntegerToRomanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java)
             * [IPConverterTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IPConverterTest.java)
+            * [IPv6ConverterTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java)
             * [MorseCodeConverterTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/MorseCodeConverterTest.java)
             * [OctalToBinaryTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java)
             * [OctalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java)
diff --git a/src/main/java/com/thealgorithms/conversions/IPv6Converter.java b/src/main/java/com/thealgorithms/conversions/IPv6Converter.java
new file mode 100644
index 00000000..d42ffd02
--- /dev/null
+++ b/src/main/java/com/thealgorithms/conversions/IPv6Converter.java
@@ -0,0 +1,98 @@
+package com.thealgorithms.conversions;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+
+/**
+ * A utility class for converting between IPv6 and IPv4 addresses.
+ *
+ * - Converts IPv4 to IPv6-mapped IPv6 address.
+ * - Extracts IPv4 address from IPv6-mapped IPv6.
+ * - Handles exceptions for invalid inputs.
+ *
+ * @author Hardvan
+ */
+public final class IPv6Converter {
+    private IPv6Converter() {
+    }
+
+    /**
+     * Converts an IPv4 address (e.g., "192.0.2.128") to an IPv6-mapped IPv6 address.
+     * Example: IPv4 "192.0.2.128" -> IPv6 "::ffff:192.0.2.128"
+     *
+     * @param ipv4Address The IPv4 address in string format.
+     * @return The corresponding IPv6-mapped IPv6 address.
+     * @throws UnknownHostException If the IPv4 address is invalid.
+     * @throws IllegalArgumentException If the IPv6 address is not a mapped IPv4 address.
+     */
+    public static String ipv4ToIpv6(String ipv4Address) throws UnknownHostException {
+        if (ipv4Address == null || ipv4Address.isEmpty()) {
+            throw new UnknownHostException("IPv4 address is empty.");
+        }
+
+        InetAddress ipv4 = InetAddress.getByName(ipv4Address);
+        byte[] ipv4Bytes = ipv4.getAddress();
+
+        // Create IPv6-mapped IPv6 address (starts with ::ffff:)
+        byte[] ipv6Bytes = new byte[16];
+        ipv6Bytes[10] = (byte) 0xff;
+        ipv6Bytes[11] = (byte) 0xff;
+        System.arraycopy(ipv4Bytes, 0, ipv6Bytes, 12, 4);
+
+        // Manually format to "::ffff:x.x.x.x" format
+        StringBuilder ipv6String = new StringBuilder("::ffff:");
+        for (int i = 12; i < 16; i++) {
+            ipv6String.append(ipv6Bytes[i] & 0xFF);
+            if (i < 15) {
+                ipv6String.append('.');
+            }
+        }
+        return ipv6String.toString();
+    }
+
+    /**
+     * Extracts the IPv4 address from an IPv6-mapped IPv6 address.
+     * Example: IPv6 "::ffff:192.0.2.128" -> IPv4 "192.0.2.128"
+     *
+     * @param ipv6Address The IPv6 address in string format.
+     * @return The extracted IPv4 address.
+     * @throws UnknownHostException If the IPv6 address is invalid or not a mapped IPv4 address.
+     */
+    public static String ipv6ToIpv4(String ipv6Address) throws UnknownHostException {
+        InetAddress ipv6 = InetAddress.getByName(ipv6Address);
+        byte[] ipv6Bytes = ipv6.getAddress();
+
+        // Check if the address is an IPv6-mapped IPv4 address
+        if (isValidIpv6MappedIpv4(ipv6Bytes)) {
+            byte[] ipv4Bytes = Arrays.copyOfRange(ipv6Bytes, 12, 16);
+            InetAddress ipv4 = InetAddress.getByAddress(ipv4Bytes);
+            return ipv4.getHostAddress();
+        } else {
+            throw new IllegalArgumentException("Not a valid IPv6-mapped IPv4 address.");
+        }
+    }
+
+    /**
+     * Helper function to check if the given byte array represents
+     * an IPv6-mapped IPv4 address (prefix 0:0:0:0:0:ffff).
+     *
+     * @param ipv6Bytes Byte array representation of the IPv6 address.
+     * @return True if the address is IPv6-mapped IPv4, otherwise false.
+     */
+    private static boolean isValidIpv6MappedIpv4(byte[] ipv6Bytes) {
+        // IPv6-mapped IPv4 addresses are 16 bytes long, with the first 10 bytes set to 0,
+        // followed by 0xff, 0xff, and the last 4 bytes representing the IPv4 address.
+        if (ipv6Bytes.length != 16) {
+            return false;
+        }
+
+        for (int i = 0; i < 10; i++) {
+            if (ipv6Bytes[i] != 0) {
+                return false;
+            }
+        }
+
+        return ipv6Bytes[10] == (byte) 0xff && ipv6Bytes[11] == (byte) 0xff;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java b/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java
new file mode 100644
index 00000000..443f865a
--- /dev/null
+++ b/src/test/java/com/thealgorithms/conversions/IPv6ConverterTest.java
@@ -0,0 +1,64 @@
+package com.thealgorithms.conversions;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.net.UnknownHostException;
+import org.junit.jupiter.api.Test;
+
+public class IPv6ConverterTest {
+
+    private static final String VALID_IPV4 = "192."
+        + "0."
+        + "2."
+        + "128";
+    private static final String EXPECTED_IPV6_MAPPED = ":"
+        + ":ff"
+        + "ff"
+        + ":19"
+        + "2."
+        + "0."
+        + "2.128";
+    private static final String INVALID_IPV6_MAPPED = "2001:"
+        + "db8"
+        + ":"
+        + ":1";
+    private static final String INVALID_IPV4 = "999."
+        + "999."
+        + "999."
+        + "999";
+    private static final String INVALID_IPV6_FORMAT = "invalid:ipv6"
+        + "::address";
+    private static final String EMPTY_STRING = "";
+
+    @Test
+    public void testIpv4ToIpv6ValidInput() throws UnknownHostException {
+        String actualIpv6 = IPv6Converter.ipv4ToIpv6(VALID_IPV4);
+        assertEquals(EXPECTED_IPV6_MAPPED, actualIpv6);
+    }
+
+    @Test
+    public void testIpv6ToIpv4InvalidIPv6MappedAddress() {
+        assertThrows(IllegalArgumentException.class, () -> IPv6Converter.ipv6ToIpv4(INVALID_IPV6_MAPPED));
+    }
+
+    @Test
+    public void testIpv4ToIpv6InvalidIPv4Address() {
+        assertThrows(UnknownHostException.class, () -> IPv6Converter.ipv4ToIpv6(INVALID_IPV4));
+    }
+
+    @Test
+    public void testIpv6ToIpv4InvalidFormat() {
+        assertThrows(UnknownHostException.class, () -> IPv6Converter.ipv6ToIpv4(INVALID_IPV6_FORMAT));
+    }
+
+    @Test
+    public void testIpv4ToIpv6EmptyString() {
+        assertThrows(UnknownHostException.class, () -> IPv6Converter.ipv4ToIpv6(EMPTY_STRING));
+    }
+
+    @Test
+    public void testIpv6ToIpv4EmptyString() {
+        assertThrows(IllegalArgumentException.class, () -> IPv6Converter.ipv6ToIpv4(EMPTY_STRING));
+    }
+}