-
Notifications
You must be signed in to change notification settings - Fork 3
Working with IP Addresses
Zane Hooper edited this page Mar 16, 2017
·
15 revisions
Create IpAddress
objects out of strings.
$ips = app(App\Ip\IpService::class);
$text = implode("\n", [
"some useless text 1.1.1.1",
"more useless stuff 1.2.3.4, 1.2.3.4/29",
]);
$result = $ips->find($text)->map(_call('__toString'))->all();
$result = [
"1.2.3.0/29",
"1.1.1.1",
"1.2.3.4",
];
$result = $ips->make("127.0.0.1");
$result->forDB(); // == \DB::raw("X'".$result->hex()."'") == \DB::raw("X'7f000001'")
$result->hex(); // == '7f000001'
$result->str(); // == (string) $result == '127.0.0.1'
$result->binary(); // == inet_pton('127.0.0.1') == "\x7F\0\0\x01"
$result->asLong(); // == 2130706433
IPs should be stored using the IP Custom Type. This is a binary representation of the IP which can be used to easily and efficiently compute IP overlaps. Note that the IP custom type can store an IPv6 or IPv4 address. The database representation of an IpAddress
is computed with the ->hex()
method, but it is best to use the ->forDB()
method which wraps it in a DB expression, adding the required X'<value>'
to specify to MySQL that it is in hexadecimal format.
Use App\Entity\LookupService
to find Entities that overlap with a specific IP or IP Range:
$range = $this->ips->make('127.0.0.1-3');
$this->lookup->overlapping($range)->get(); // [ Entity<127.0.0.1>, Entity<127.0.0.2-5> ]
$this->lookup->addr($range); // Entity<127.0.0.1>
$range = $this->ips->make('127.0.0.5');
$this->lookup->overlapping($range)->get(); // [ Entity<127.0.0.2-5> ]