Last active
April 23, 2023 14:16
-
-
Save rbw/17cad5ab6ec9ca3e7b0addc34907132a to your computer and use it in GitHub Desktop.
Non-blocking tcp scanner in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Optional mappings | |
$port_service = array( | |
20 => "ftp-data", | |
21 => "ftp", | |
22 => "ssh", | |
23 => "telnet", | |
24 => "priv-mail", | |
25 => "smtp", | |
53 => "domain", | |
80 => "http", | |
110 => "pop3", | |
119 => "nntp", | |
135 => "msrpc", | |
143 => "imap", | |
220 => "imap3", | |
443 => "https", | |
993 => "imaps", | |
1248 => "hermes", | |
3306 => "mysql", | |
5432 => "postgresql", | |
5666 => "nrpe", | |
6556 => "check_mk", | |
9999 => "abyss" | |
); | |
class Scanner { | |
private $host; | |
function __construct($host) { | |
$this->host = $host; | |
} | |
private function sockets_create($host, $ports) { | |
$sockets = []; | |
foreach($ports as $port) { | |
$socket = socket_create(AF_INET , SOCK_STREAM , SOL_TCP); | |
socket_set_nonblock($socket); | |
@socket_connect($socket, $host, $port); | |
$sockets[$port] = $socket; | |
} | |
return $sockets; | |
} | |
private function sockets_poll($sockets) { | |
global $port_service; | |
$ports_open = []; | |
$start = microtime(true); | |
while ($sockets && microtime(true) - $start < 3) { | |
$null = null; | |
$write = $sockets; | |
socket_select($null, $write, $null, 0, 50000); | |
foreach ($write as $port => $sock) { | |
// @TODO - check for SOCKET_ETIMEDOUT and SOCKET_ECONNREFUSED if needed | |
if (socket_get_option($sock, SOL_SOCKET, SO_ERROR) === 0) { | |
$service = array_key_exists($port, $port_service) ? $port_service[$port]:"Unknown"; | |
array_push($ports_open, ["number"=>$port, "service"=>$service]); | |
} | |
unset($sockets[$port]); | |
socket_close($sock); | |
} | |
} | |
return $ports_open; | |
} | |
public function probe_ports($ports) { | |
$sockets = $this->sockets_create($this->host, $ports); | |
return $this->sockets_poll($sockets); | |
} | |
} | |
$scanner = new Scanner("google.com"); | |
$open = $scanner->probe_ports([22, 80, 53, 111, 8080]); | |
print_r($open, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment