Link to home
Start Free TrialLog in
Avatar of ldorazio
ldorazio

asked on

From IP address, extract just the first three octets (network) from the address using PHP

I want to extract just the first three octets (the network basically) from an IP address with PHP.

I have an IP address (i.e.  1.2.3.4)
and I want to extract just the:   1.2.3    part

It could be 1, 2 or 3 numbers per octet (since it's an IP address):
   could be:             I want:
  192.168.0.1   -->  192.168.0
  10.1.102.3    -->   10.1.102

etc.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of b0lsc0tt
b0lsc0tt
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi ldorazio,

Well, since there are always at least three parts, you can just do:

$ip = '192.168.0.1';
$cut_ip = substr($ip, 0, strrpos($ip, '.'));
echo($cut_ip);

Regards,
Ted
Heh, didn't see your post, b0lsc0tt. My bad.

Ted
@Zyloch - No problem!  I have been on the other side often too.  Posted at essentially the same time and I have no problem splitting if our answers help him.

bol
Don't worry about the split. The points are rightfully yours, and I don't care so much for them anyhow :P It's interesting how our answers are essentially the same though, hehe

Ted
@Zyloch, I was not watching what you typed! :D  With your expertise in this area I am glad to see your similar post.  I'll be fine with whatever Idorazio decides to do regarding points.

bol
Silly idea, but ... (untested) ...

<?php
$s_ip = '192.168.0.1';
$i_ip = ip2long($s_ip);
$i_ip = $i_ip & ~255;
$s_ip = long2ip($i_ip);
$s_ip = substr($s_ip, 0, -2);
?>

Take the string. Convert it to a long using ip2long(). Mask off the lower 8 bits. Convert it back to an IP which will now end in ".0". Substr to drop off the last 2 characters.

I doubt I'd actually do it this way, but an exercise all the same.

And at least it is actually using a mask! So MAYBE has more relevance than just string manipulation.

Avatar of ldorazio
ldorazio

ASKER

Awesome, thank you!

Sometimes I can't think the right way, and I was in a hurry so I appreciate the quick answers.
A completely useless example of masking. I had a spare 10 mins whilst a backup was running.

<?php
function maskIP($s_IP, $i_bits)
      {
      $i_IP = ip2long($s_IP);
      $i_mask = ($i_bits > 0) ? pow(2, $i_bits) - 1 : 0;
      $i_IP &= ~$i_mask;
      $s_IP = long2ip($i_IP);
      return $s_IP;
      }

$s_IP = rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255);
$i_mask = rand(0, 32);
echo $s_IP . ' mask ' . $i_mask . ' is ' . maskIP($s_IP, $i_mask) . "\n";
?>
Your welcome!  I'm glad that I could help you and I enjoyed participating with the others in this.  Thank you for the grade, the points and the fun question.

bol