gethostbyname php,PHP: gethostbyname bug

本文探讨了PHP内置函数gethostbyname()如何处理无效IP地址,如'50.9.49',实际上将其转换为50.9.0.49。作者揭示了该问题背后的原理,并提供了解决方案,包括在调用前检查数值格式。同时,文中提到了Windows和Linux系统中IP地址输入的特殊行为。
摘要由CSDN通过智能技术生成

问题

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?

回答1:

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));

}

/* }}} */

回答2:

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.

来源:https://stackoverflow.com/questions/10623408/php-gethostbyname-bug

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值