IPv4.php
2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/**
* Created by PhpStorm.
* User: eduardo
* Date: 14/04/14
* Time: 11:23
*/
namespace Cacic\WSBundle\Helper;
/******************************************
* IPv4 Network Class
* Author: Mike Mackintosh
* Date: 12/27/2011 2121
*
* @Usage: new IPv4 ('10.1.1.1', 28);
*
* Source: http://www.highonphp.com/tag/php-subnet-calculator
*
*****************************************/
class IPv4
{
private $ip_long;
public $ip;
public $cidr;
function __construct($ip,$cidr)
{
$this->ip = $ip;
$this->ip_long = ip2long($ip);
$this->cidr = $cidr;
}
function __toString(){
$methods = get_class_methods($this);
foreach($methods as $meth){
if(substr($meth, 0, 2) != '__' && $meth != 'mask2cidr' && $meth != 'cidr2mask'){
$r[] = $this->$meth();
}
}
return json_encode($r);
}
static function mask2cidr($mask)
{
$mask = ip2long($mask);
$base = ((1<<32)-1);
return 32-log(($mask ^ $base)+1,2);
}
static function cidr2mask($cidr)
{
$mask = ip2long('255.255.255.255');
$base = ((1<<$cidr)-1);
return 32-log(($mask ^ $base)+1,2);
}
function address(){
return $this->ip;
}
function cidr() {
return $this->cidr;
}
function netmask()
{
$netmask = ((1<<32) -1) << (32-$this->cidr);
return long2ip($netmask);
}
function network()
{
$network = $this->ip_long & (ip2long($this->netmask()));
return long2ip($network);
}
function broadcast()
{
$broadcast = ip2long($this->network()) | (~(ip2long($this->netmask())));
return long2ip($broadcast);
}
function wildcard()
{
$inverse = ~(((1<<32) -1) << (32-$this->cidr));
return long2ip($inverse);
}
function availablehosts()
{
$hosts = (ip2long($this->broadcast()) - ip2long($this->network())) -1;
return $hosts;
}
function availablenetworks()
{
return pow(2, 24)/($this->availablehosts()+2);
}
}