基于PHP实现端口批量查询工具
Here's the PHP code for a port scanner tool that allows you to scan a range of IP addresses and ports for open connections:
PHP
<?php
class PortScanner {
private $ipRange;
private $portRange;
private $timeout;
public function __construct($ipRange, $portRange, $timeout = 1) {
$this->ipRange = $ipRange;
$this->portRange = $portRange;
$this->timeout = $timeout;
}
public function scan() {
$openPorts = [];
foreach ($this->getIPs() as $ip) {
foreach ($this->getPorts() as $port) {
if ($this->isPortOpen($ip, $port)) {
$openPorts[] = ["IP: $ip", "Port: $port"];
}
}
}
return $openPorts;
}
private function getIPs() {
$ips = [];
$ipRangeParts = explode('-', $this->ipRange);
$startIP = ip2long($ipRangeParts[0]);
$endIP = ip2long($ipRangeParts[1]);
for ($ip = $startIP; $ip <= $endIP; $ip++) {
$ips[] = long2ip($ip);
}
return $ips;
}
private function getPorts() {
$ports = [];
$portRangeParts = explode('-', $this->portRange);
$startPort = intval($portRangeParts[0]);
$endPort = intval($portRangeParts[1]);
for ($port = $startPort; $port <= $endPort; $port++) {
$ports[] = $port;
}
return $ports;
}
private function isPortOpen($ip, $port) {
$socket = @fsockopen($ip, $port, $errno, $errstr, $this->timeout);
if ($socket) {
fclose($socket);
return true;
} else {
return false;
}
}
}
// Example usage
$scanner = new PortScanner('192.168.1.0-192.168.1.255', '25-80');
$openPorts = $scanner->scan();
if ($openPorts) {
echo "Open ports:\n";
foreach ($openPorts as $portInfo) {
echo " - " . implode(' ', $portInfo) . "\n";
}
} else {
echo "No open ports found in the specified range.\n";
}
Explanation:
PortScanner Class:
__construct(): Initializes the class with the IP range ($ipRange), port range ($portRange), and timeout ($timeout).scan(): The main scanning function.
getIPs() and getPorts() methods.isPortOpen() to check if the port is open.$openPorts array.$openPorts array.getIPs(): Expands the IP range string (192.168.1.0-192.168.1.255) into an array of individual IP addresses using ip2long() and long2ip().getPorts(): Creates an array of ports within the specified range (25-80) using a simple loop.isPortOpen(): Checks if a specific port on an IP is open using fsockopen().
true if the port is open, false otherwise.Example Usage:
PortScanner object with the desired IP and port ranges.scan() to perform the port scan.$openPorts).Key Points:
isPortOpen() function to handle different types of ports (e.g., TCP, UDP) and more advanced error handling.
《无所畏惧》温莉的结局是什么
时间:2023-11-25
《无所畏惧》刘铭的结局是什么
时间:2023-11-25
《无所畏惧》罗英子和陈硕最后在一起了吗
时间:2023-11-25
《宁安如梦》 姜雪宁是如何设计让薛姝去和亲
时间:2023-11-25
《宁安如梦》薛姝为了不和亲做了什么
时间:2023-11-25
《宁安如梦》为什么姜雪蕙只能当侧妃
时间:2023-11-25