Search code examples
phpipgethostbyaddr

Invalid IP Address with multi-line IP Address


I am stuck with this error while trying to read a file which holds IP addresses separated by a new line. What I want to do, is to read my file that holds bunch of IP's and check does they have proper record. This is my code:

$file = "test.sh";

if (is_file($file) && is_readable($file)) {
    $get_file_data = file_get_contents($file);

    $turn_to_array = explode("\n", $get_file_data);

    foreach ($turn_to_array as $key => $value) {

        if (filter_var($value, FILTER_VALIDATE_IP)) {
            echo gethostbyaddr(trim($value));
        } else {
            echo "IP invalid";
        }
    }
}

My test.sh file looks like following:

EDIT : example IP's

180.1.1.1
181.1.1.2

Do I need to add some specific tests to parse a file or there is some other issue?

The error caused by the very unique method used:

Warning: gethostbyaddr(): Address is not a valid IPv4 or IPv6 PHP

Solved.

My code was working, I wasn't getting rdns record properly, since it didn't exist for those IP's. I've checked it with host 185.1.1.1 and it returned actual IP not domain. Then checked IP's for whom I was sure that they have PTR records, and it woked. But I am not sure exactly how error was fixed actually.


Solution

  • I'm going to be honest, I think exploding the raw file data and hoping for the best may not be the best way to accomplish this. Instead, you should try to extract the exact data you need using regular expressions so you are certain you are extracting the correct values.

    Try something like this:

    $data = file_get_contents($file);
    
    // This regex matches things that resemble an IP4 address
    if (preg_match_all("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/", $data, $addresses)) {
    
        foreach ($addresses as $address) {
    
            // Need to verify it ACTUALLY is a valid IP address
            if (filter_var($address, FILTER_VALIDATE_IP)) { 
    
                echo gethostbyaddr($address);
    
            }
    
        }
    
    }
    

    NOTE: The regex used here was written by @alex here: Regex to match an IP address

    If this doesn't help, then it may be a configuration issue. A few other things to check that might help with troubleshooting are:

    • Does gethostbyaddr('127.0.0.1'); throw the same error?
    • Do you have a firewall that prevents the DNS request from going through?
    • Can you use the dig command from the server to issue a lookup on the IP?