使用 PHP 检查 IPv4/IPv6 地址是否可用

Check If IPv4/IPv6 Address is up using PHP

我有一个 IPv4 地址。前任。 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 地址 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 寻找其他解决方案?

解析 IP 地址的内置方法是 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.

要确定格式,您可以计算结果字节数:

strlen(inet_pton($ip))
4 bytes = 32 bits = IPv4
16 bytes = 128 bits = IPv6

(不过,在您的确切用例中,您一开始就不清楚为什么需要它。)