Created
July 10, 2025 05:51
-
-
Save moriarty99779/de413b0b045eb0dbb11793047d4eb16a to your computer and use it in GitHub Desktop.
PHP Class to Scan Ports
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 | |
class PortScanner { | |
private $subnet; | |
private $ports; | |
private $timeout; | |
public function __construct($subnet, $ports = [80, 443, 22, 21, 23], $timeout = 1) { | |
$this->subnet = $subnet; // The local subnet in CIDR notation (e.g., 192.168.1.0/24) | |
$this->ports = $ports; // Array of ports to scan (default: HTTP, HTTPS, SSH, FTP, Telnet) | |
$this->timeout = $timeout; // Timeout for each connection attempt (in seconds) | |
} | |
// Generate all IPs in the subnet | |
private function generateIPs() { | |
$subnetParts = explode('.', $this->subnet); | |
$baseIP = implode('.', array_slice($subnetParts, 0, 3)) . '.'; | |
$startRange = (int)$subnetParts[3]; | |
$ips = []; | |
for ($i = 1; $i < 255; $i++) { | |
$ips[] = $baseIP . ($startRange + $i); | |
} | |
return $ips; | |
} | |
// Check if a given IP address has a port open | |
private function checkPort($ip, $port) { | |
$connection = @fsockopen($ip, $port, $errno, $errstr, $this->timeout); | |
if (is_resource($connection)) { | |
fclose($connection); | |
return true; | |
} | |
return false; | |
} | |
// Scan a host for open ports | |
public function scan() { | |
$openPorts = []; | |
$ips = $this->generateIPs(); | |
foreach ($ips as $ip) { | |
foreach ($this->ports as $port) { | |
if ($this->checkPort($ip, $port)) { | |
echo "Host: $ip, Port: $port is open.\n"; | |
$openPorts[$ip][] = $port; | |
} | |
} | |
} | |
return $openPorts; | |
} | |
} | |
// Example usage: | |
$scanner = new PortScanner('192.168.1.0', [80, 443, 22]); // Use your local subnet and preferred ports | |
$openPorts = $scanner->scan(); | |
echo "Open ports found:\n"; | |
print_r($openPorts); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment