MilosM MilosM - 1 year ago 221
PHP Question

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

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 = "";

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 file looks like following:

example IP's

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


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 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.

Answer Source

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(''); 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?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download