code-8
code-8

Reputation: 58662

Check If IPv4/IPv6 Address is up using PHP

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 ?

Upvotes: 2

Views: 2450

Answers (1)

Álvaro González
Álvaro González

Reputation: 146460

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.)

Upvotes: 3

Related Questions