February 23, 2015

PHP asynchronous host scanner on Windows

The following PHP code scans IP range 192.168.5.1-192.168.5.254 in 3 seconds and returns the reachable hosts.

<?php
$timeout=3;

function ping($host, $timeout = 1) {
/* ICMP ping packet with a pre-calculated checksum */
$package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
$socket  = socket_create(AF_INET, SOCK_RAW, 1);
socket_connect($socket, $host, null);

$ts = microtime(true);
socket_send($socket, $package, strLen($package), 0);
return $socket;
}

$read=array();
for ($i=1;$i<255;$i++){
$host="192.168.5.$i";
$socket=ping($host);
$read[]=$socket;
}

$read0=$read;
$mynil=NULL;
$timeout_us=0;
$endtime=microtime(true)+$timeout;
while(true){
$ret=socket_select($read,$mynil,$mynil,$timeout,$timeout_us);
if ($ret==0){
die("Done\n");
}
if ($ret>0){
foreach ($read as $sock){
$address="";
socket_getpeername($sock,$address);
echo "$address\n";
}
$read=array_diff($read0,$read);
$read0=$read;
$newtimeout=$endtime-microtime(true);
$timeout=floor($newtimeout);
$timeout_us=$newtimeout-$timeout;
}
}

No comments:

Post a Comment