How do I reverse an IP address for use in DNS BL?

Here’s a small function in PHP 8.3 that reverses an IPv4 address:

<?php
function reverseIPv4(string $ip): string {
    // Validate if the input is a valid IPv4 address
    if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        throw new InvalidArgumentException("Invalid IPv4 address provided.");
    }
    
    // Split the IP into segments, reverse them, and join back
    return implode('.', array_reverse(explode('.', $ip)));
}

// Example usage
try {
    $originalIP = "192.168.1.1";
    $reversedIP = reverseIPv4($originalIP);
    echo "Original IP: $originalIP\n";
    echo "Reversed IP: $reversedIP\n";
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Explanation:

  1. Validation: The filter_var function checks if the input is a valid IPv4 address.
  2. Splitting and Reversing: The explode function splits the IP by dots, array_reverse reverses the segments, and implode joins them back into a string.
  3. Exception Handling: If the input is not a valid IPv4 address, an exception is thrown to handle the error gracefully.

This ensures the function works safely and as expected.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *