问题
I have an IPv4 address. Ex. 172.19.20.21
I used to do this
$fs = @fsockopen($ip,$port,$errno,$errstr,3);
if( !$fs ){
$error = 'SSC is down';
return Redirect::to('/')->with('error', $error )
->withInput(Request::except('password'));
}
It works perfectly fine.
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'));
}
}
Can I use this code above ? Or I need to look for other solution for IPv6 ?
回答1:
The builtin way to parse an IP address is inet_pton():
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.)
来源:https://stackoverflow.com/questions/43298670/check-if-ipv4-ipv6-address-is-up-using-php