domovoy/app/Services/Discovery/TcpPortScanner.php

42 lines
1006 B
PHP

<?php
declare(strict_types=1);
namespace Domovoy\Services\Discovery;
class TcpPortScanner
{
/**
* Scan a list of TCP ports on a host.
*
* @param int[] $ports
* @param int $timeoutMs connection timeout per port
* @param int $maxConcurrency max parallel connections
* @return int[] list of open ports
*/
public function scan(string $ip, array $ports, int $timeoutMs = 200, int $maxConcurrency = 50): array
{
$openPorts = [];
$timeoutSec = $timeoutMs / 1000;
foreach ($ports as $port) {
$errno = 0;
$errstr = '';
$fp = @stream_socket_client(
"tcp://{$ip}:{$port}",
$errno,
$errstr,
$timeoutSec,
STREAM_CLIENT_CONNECT
);
if ($fp !== false) {
$openPorts[] = $port;
fclose($fp);
}
}
sort($openPorts);
return $openPorts;
}
}