6

I am using gethostbyname() to get the ip address of domains in an application.

In some cases invalid addresses like '50.9.49' are checked also.

echo gethostbyname('50.9.49'); // returns 50.9.0.49

In this cases gethostbyname should return false or the unmodified invalid ip address. however the functions returns the modified IP address 50.9.0.49.

Looks like a bug in php. The quick fix seems to be to check for invalid numerical addresses before, are there any other suggestions?

7
  • 3
    I think PHP is not the only place where this happens. It also happens when using ping 50.9.49 in Windows. I get the response: Pinging 50.9.0.49 with 32 bytes of data... May 16, 2012 at 17:17
  • @Simon In that case its not bug May 16, 2012 at 17:19
  • 2
    it's not a bug ... it's a feature! ;-)
    – aurora
    May 16, 2012 at 17:22
  • And ping 173.1 would actually ping 173.0.0.1.
    – Susam Pal
    May 16, 2012 at 17:23
  • 1
    Its some kind assuming 0s in the middle to make it 4 byte long address. May 16, 2012 at 17:24

2 Answers 2

7

PHP's gethostbyname actually uses the results of the underlying OS's gethostbyname, e.g., from Linux's netdb.h or Windows' Winsock2.h. It's those functions that actually produce the return value, not PHP.

/* {{{ php_gethostbyname */
static char *php_gethostbyname(char *name)
{
    struct hostent *hp;
    struct in_addr in;

    hp = gethostbyname(name);

    if (!hp || !*(hp->h_addr_list)) {
        return estrdup(name);
    }

    memcpy(&in.s_addr, *(hp->h_addr_list), sizeof(in.s_addr));

    return estrdup(inet_ntoa(in));
}
/* }}} */
3

It seems like this is an undocumented feature for how IPs works. As mentioned in the comments for your question, ping 50.9.49 in Windows actually pings 50.9.0.49. If you enter an adress as a.b.d, it automatically inserts a zero as c: a.b.0.d. If you just enter a.d, two zeroes are inserted: a.0.0.d.

This has been tested with both Windows 7 and Debian Linux.

2
  • 1
    It actually goes further than that -- the third "octet" is treated as a 16-bit value. Pinging 1.2.772 gets you 1.2.3.4, since 772 is 0x0304. Indeed, you can ping 16909060 (0x01020304) to get the same result!
    – user149341
    May 16, 2012 at 17:42
  • 1
    ping 50 gets you 0.0.0.50. May 16, 2012 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.