使用PHP检查IPv4/IPv6地址是否已启动 [英] Check If IPv4/IPv6 Address is up using PHP
问题描述
我有一个IPv4地址.前任. 172.19.20.21
I have an IPv4 address. Ex. 172.19.20.21
我曾经这样做
$fs = @fsockopen($ip,$port,$errno,$errstr,3);
if( !$fs ){
$error = 'SSC is down';
return Redirect::to('/')->with('error', $error )
->withInput(Request::except('password'));
}
它工作得很好.
现在,我有一个IPv6地址. 3000::1
Now, I have an IPv6 Address Ex. 3000::1
if ((strpos($ip, ":") > -1)){
// Code for IPv6 check
$fs = @fsockopen($ip,$port,$errno,$errstr,3);
if( !$fs ){
$error = 'SSC is down';
return Redirect::to('/')->with('error', $error )
->withInput(Request::except('password'));
}
}else{
// Code for IPv4 check
$fs = @fsockopen($ip,$port,$errno,$errstr,3);
if( !$fs ){
$error = 'SSC is down';
return Redirect::to('/')->with('error', $error )
->withInput(Request::except('password'));
}
}
我可以在上面使用此代码吗?还是我需要寻找其他IPv6解决方案?
Can I use this code above ? Or I need to look for other solution for IPv6 ?
推荐答案
解析IP地址的内置方法是 inet_pton( ):
The builtin way to parse an IP address is inet_pton():
此函数转换人类可读的IPv4或IPv6地址(如果是PHP) 是在启用IPv6支持的情况下构建的)集成到地址族中 适当的32位或128位二进制结构.
This function converts a human readable IPv4 or IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate 32bit or 128bit binary structure.
例如,要确定格式,可以计算结果字节数:
To determine the format you can, for instance, count the resulting bytes:
strlen(inet_pton($ip))
4 bytes = 32 bits = IPv4
16 bytes = 128 bits = IPv6
(不过,在您的确切用例中,目前尚不清楚为什么首先需要使用它.)
(In your precise use case, though, it's kind of unclear why you need this in the first place.)
这篇关于使用PHP检查IPv4/IPv6地址是否已启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!