Check If IPv4/IPv6 Address is up using PHP

北战南征 提交于 2021-02-08 07:59:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!