Networking utilities

When working on PHP projects, I sometimes need some networking utilities. This repository provides them. You can think about executing a ping request, scanning a network, getting IP information, etcetera.

For those purposes I wrote a library that's been tested on both Windows and Linux servers.

Below you'll find the documentation of the library. Source code can be found at https://bitbucket.org/garrcomm/php-networking-utilities.

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.