我正在尝试获取:46-121-31-23.example.net
解析为:46.121.31.23
替换连字符并使用REGEX删除字符是不够的,因为这样做的结果将是46.121.31.23..
gethostbyname()
怎么样?虽然您的特定主机名将IPv4地址编码为其"友好"名称,但不能保证这总是正确的。所以使用实名制->ip查找系统:DNS
$ip = gethostbyname('46-121-31-23.example.net');
echo $ip; // 46.121.31.23
评论后续:该主机名显然不存在:
marc@panic:~$ host -t ns static.012.net.il
static.012.net.il name server pdns.goldenlines.net.il.
static.012.net.il name server sdns.goldenlines.net.il.
marc@panic:~$ host 46-121-31-23.static.012.net.il pdns.goldenlines.net.il
Using domain server:
Name: pdns.goldenlines.net.il
Address: 212.117.129.3#53
Aliases:
Host 46-121-31-23.static.012.net.il not found: 3(NXDOMAIN)
因此没有办法进行DNS查找,因为该域的权威服务器不知道你在说什么。
然而,反向映射(IP->主机名)确实有效:
marc@panic:~$ host 46.121.31.23
23.31.121.46.in-addr.arpa domain name pointer 46-121-31-23.static.012.net.il.
因此,出于某种原因,该提供程序只进行反向映射,而不进行正向映射。
if (preg_match('/('d{1,3})-('d{1,3})-('d{1,3})-('d{1,3})/', $hostname, $ip)) {
$ip = "{$ip[1]}.{$ip[2]}.{$ip[3]}.{$ip[4]}";
}
应该有效。
类似的东西?
$ip = preg_replace("/'..*/", "", $ip);
$ip = str_replace("-", ".", $ip);
不过,我同意@klaustopher的观点,即使用gethostbyname
通常更安全:(http://php.net/manual/en/function.gethostbyname.php)。
编辑:
另外,你可以尝试这样做:不使用gethostbyname从DNS获取IP?