Unfortunately, I can't get this to work on Azure Web App, however I think this would work in other scenarios, where you are running your own server.
class netstat {
public $PortsInUse = 0;
public $AvailablePorts = 0;
public $TotalPorts = 0;
public $Ports = array();
public function __construct () {
$p = popen('netsh int ipv4 show dynamicport tcp', 'r');
$this->TotalPorts = rtrim(trim(explode("Number of Ports : ", stream_get_contents($p))[1]));
pclose($p);
$netstat = popen('netstat -no', 'r');
$log = stream_get_contents($netstat);
pclose($netstat);
$this->Ports = array_slice(explode("
", $log), 4);
array_pop($this->Ports);
foreach($this->Ports as &$port) {
$port = explode(" ", $port);
foreach($port as $k => $p) {
if (empty($p))
unset($port[$k]);
}
$port = array_values($port);
$port = (object)array(
"LocalAddress" => $port[0],
"ForeignAddress" => $port[1],
"Status" => $port[2],
"ProcessId" => $port[3]
);
}
$this->PortsInUse = count($this->Ports);
$this->AvailablePorts = $this->TotalPorts - count($this->Ports);
}
}
The above object will be able to display the current number of TCP ports in use, and the total number of dynamic ports available for TCP on that machine. It also contains a "Ports" array, which contains information about each port in use, such as their local and foreign address, status and PID (process id).