IPv4 class
In my previous article I tried to argue the benefits of using objects to represent domain names, ip addresses and email addresses, although the same argument extends to other fixed-format strings as well. This article is the second installment of the series: the ip-address.
More specifically, the class shown below represents an IPv4 address, soon to be replaced by the IPv6 address. Until that happens though, this will do just fine.
class.IPv4.php
<?php
/*
* Represents an IPv4 address
*/
class IPv4
{
/*
* Constructs a new IP object from the given string, expects something of
* the form 255.255.255.255 (dot-decimal notation)
*/
public function __construct($ip)
{
$parts = self::parse($ip);
if ($parts === false) throw new Exception('Invalid IP address passed to constructor');
$this->parts = $parts;
}
/*
* Splits an IP address (of the form int.int.int.int) into four parts and
* returns them. Returns false if the address is invalid
*/
public static function parse($ip)
{
$arr = explode('.', $ip);
if (count($arr) != 4) return false;
foreach ($arr as $part) {
if (!is_numeric($part)) return false;
$part = intval($part);
if ($part < 0 || $part > 255) return false;
}
return $arr;
}
/*
* Returns a string representation of the ip address
*/
public function __toString()
{
return implode('.', $this->parts);
}
/*
* Returns the ip address as four decimal parts
*/
public function getParts()
{
return $this->parts;
}
/*
* Returns the reverse root ip address using the extension in-addr.arpa,
* useful for DNS purposes only
*/
public function getAsArpa()
{
$out = "";
for ($i=2; $i>=0; $i--) $out .= $this->parts[$i] . '.';
$out .= 'in-addr.arpa';
return $out;
}
/*
* Returns the last part of the ip address
*/
public function getLast()
{
return $this->parts[3];
}
private $parts;
}
?>
The funny methods getLast() and getAsArpa() were added specifically for use in a DNS program and might find not much general use. (how often do you need to reverse an IP addres...)
Next up: the email address, which can end in either a domain name or an ip-address
Jul 9th, 2008
Comments
No comments yet! Feel free to post some using the form below.
If you wish to add code to your comment you can use code tags, like this: <code class="php">yourCodeHere</code>.
Quite a large number of languages are supported, although I can't guarantee it'll be pretty. Inside the code tags you can use any characters except for the string "</code>".