garrcomm/networking-utilities

PHP library containing some networking utilities

dev-master 2023-07-07 08:32 UTC

This package is auto-updated.

Last update: 2024-04-07 10:02:10 UTC


README

When working on PHP projects, I sometimes need some networking utilities. This repository provides them.

What's included?

Currently the utilities below are included. More will be added when I have the need for them.

$tools = new \Garrcomm\Netutils\Service\IpTools();

// getLocalIpv4s() returns a list of all IPv4 addresses on the current machine
$ips = $tools->getLocalIpv4s();
foreach ($ips as $networkName => $ip) {
    echo 'Network ' . $networkName . ' has IP address ' . $ip->getIpAddress() . PHP_EOL;
}

// networkQuickScan returns a list of all IPv4 addresses that can be found within a network
$ip = new \Garrcomm\Netutils\Model\Ipv4Address('192.168.2.1', '255.255.255.0');
$ips = $tools->networkQuickScan($ip);
foreach ($ips as $mac => $ip) {
    echo 'System ' . $mac . ' has IP address ' . $ip->getIpAddress() . PHP_EOL;
}

// With getIpByMac you can get the IP based on a MAC address
$mac = new \Garrcomm\Netutils\Model\MacAddress('aa-bb-cc-dd-ee-ff');
$ip = $tools->getIpByMac($mac);
echo 'Mac address ' . $mac . ' resolves to ' . $ip . PHP_EOL;

// With isLocalIp you can look up if an IP address is a local IP address
$ips = ['192.168.0.1', '8.8.8.8', '10.0.0.1'];
foreach ($ips as $ip) {
    echo $ip . ' is ' . ($tools->isLocalIp($ip) ? 'a' : 'not a') . ' local IP' . PHP_EOL;
}

OS Dependencies

These utilities should work on most Windows and Linux installations. For Linux, it can be possible that you'll need to install some additional packages (depending on the OS config we'll need the commands ip, ifconfig, ping and/or arp). Whenever one of those commands is missing, a RuntimeException with code 127 will be thrown.

On most Linux distros these tools are already included though. Otherwise it's easy to solve by locating the appropiate package (apt-file search --regexp 'bin/ping$' or yum provides ping, depending on your distro).

Tip for Windows Developers

In the bin folder, a few batch files exist, to make development easier.

If you install Docker Desktop for Windows, you can use bin\composer.bat, bin\phpstan.bat, bin\phpcs.bat, bin\phpunit.bat and bin\security-checker.bat as shortcuts for Composer, PHPStan, CodeSniffer, PHPUnit and the Security Checker, without the need of installing PHP and other dependencies on your machine.

The same Docker container and tools are used in Bitbucket Pipelines to automatically test this project.