PHP Проверка, активен ли порт
Я нахожусь в процессе создания своего собственного скрипта статуса сервиса, чтобы одновременно лучше познакомиться с языком PHP и спроектировать его с нуля как можно более эффективно для моих нужд.
Часть моего кода, используемого как в моей работе cron, так и при тестировании частей соединения, запрашивает IP / порт службы, чтобы убедиться, что она подключена к сети. Моя проблема в том, что скрипт просто запрашивает, является ли порт «разблокированным» на этом IP-адресе, поэтому, если, например, я запрашивал порт 21 с FTP-сервером, и этот FTP-сервер вышел из строя, мой скрипт не обнаружил бы никаких изменений, означающих, что он не выполняет то, что я хочу это делать. Вместо этого я хотел бы, чтобы IP-адрес и порт запрашивались, и мой сценарий мог видеть, действительно ли что-то работает на этом порту, если есть показ в сети, если нет ошибки. Я посмотрел на Google, и мне кажется, что мне нужно было бы отправить пакет / получить ответ, чтобы PHP мог сказать, что есть что-то активное? Я не уверен.
Решение
fsockopen — Открытое интернет-соединение или соединение с сокетом домена Unix. Сокет
по умолчанию будет открыт в режиме блокировки. Вы можете переключить его на
неблокирующий режим с помощью stream_set_blocking (). Функция
stream_socket_client () похожа, но предоставляет более богатый набор
варианты, в том числе неблокирующее соединение и возможность предоставления
контекст потока.
Поскольку fsockopen будет либо подключаться, либо не подключаться (тайм-аут), это говорит о том, доступно ли соединение («открыто») или заблокировано (брандмауэр и т. Д.).
// Ping by website domain name, IP address or Hostname function example_pingDomain($domain) < $starttime = microtime(true); $file = @fsockopen($domain, 80, $errno, $errstr, 10); $stoptime = microtime(true); $status = 0; if (!$file) < $status = -1; // Site is down >else < fclose($file); $status = ($stoptime - $starttime) * 1000; $status = floor($status); >return $status; >
Другие решения
Если вы действительно хотите знать, работает ли FTP-сервер или нет, лучше всего отправлять на него команды FTP.
FTP-сервер при подключении должен обычно отвечать первыми тремя байтами «220» или «120». 220 — это «приветствие». Вы можете прочитать больше в RFC 959.
Чтобы быть полностью уверенным, вам лучше использовать ftp: // обработку в PHP, например на самом деле аутентификация пользователя (может быть, аутентификация пользователя нарушена, но он все еще может отправлять приветствие — этот счет «сбит»?)
В любом случае, если вы хотите лучше, чем «смог ли я подключиться к этому порту?» или «соединение прошло своевременно?», вы должны углубиться в реальное общение через сокет. В конечном итоге это означает, что вы должны сделать что-то особенное для каждого типа сервиса (для одних — чтение байтов, для других — запись байтов и т. Д.)
How to Code a TCP Connect Port Scanner in PHP
A port scanner is a program designed to probe a server or host for open ports. Looking at open ports, one can tell what services might be running on the remote server.
Now we shall try making the same port scanner in PHP.
The code is very simple:
Using fsockopen
desktop:~$ php /var/www/blog/port_scanner.php port 21 open port 22 open port 80 open
The above code uses fsockopen to connect a host on a port , and if the connection is established then it returns true , indicating that the port is open.
Using PHP Sockets
/* Simple TCP connect port scanner in php using fsockopen */ //avoid warnings PHP Warning: fsockopen(): unable to connect to 192.168.1.2:83 (Connection refused) in /var/www/blog/port_scanner.php on line 10 error_reporting(~E_ALL); $from = 1; $to = 255; //TCP ports $host = '192.168.1.2'; //Create a socket $socket = socket_create(AF_INET , SOCK_STREAM , SOL_TCP); for($port = $from; $port >
desktop:~$ php /var/www/blog/port_scanner.php port 21 open port 22 open port 80 open
The above example uses the php socket functions socket_create and socket_connect , to connect to a host on a port.
If the connection is established the socket_connect function returns true , indicating that the port is open.
A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .
2 Comments
php check if port is open
If you want to know if a port is open, you can use the PHP port_open() function. This function returns true if the port is open. For example, if the port is open in TCP/IP, PHP will return true. However, if you want to check if a port is open in a different protocol, you should use the fsockclose() function.
How to Check If a Port is Open in PHP
fsockopen() function
PHP checks whether a port is open on a specific host using the fsockopen() function. This function will return TRUE if the connection is established. If not, it will return FALSE. Then, you can loop through the code to check the status of the connection. To use this function, you need to be on a paid hosting account.
This function has several disadvantages. It will not work properly with HTTP/1.1. HTTP/1.0 is recommended for most web applications. This is because the HTTP/1.1 protocol uses chunked data and fsockopen will produce junk in the headers and before the body content. PHP’s fsockopen() function will return false if it can’t find the certificate store.
This function initiates a stream connection in the Unix or Internet domain. It creates a TCP socket connection with hostname and port, where hostname is an IP address or a fully qualified domain name. You also have to specify a protocol, in which case udp://hostname is used. If you’re using a Unix domain, port is set to 0. The timeout parameter is optional. Afterwards, fsockopen() returns a file pointer, which can be used by other file functions.
Besides pfsockopen(), PHP also uses fsockopen(), fgets(), and socket_set_blocking() functions. With these, you can make use of UDP support. These functions make it easier to check if a port is open by implementing the fsockopen() function. In addition, they’re part of the Curl extension.
fsockclose() function
You can use the fsockopen() function to check if a port on a particular host is open. However, most free web hosting providers disable this function so you can’t use it. Fortunately, the fsockopen() function is available on paid hosting, but you can only use it if you have a paid account. However, it’s not safe to use this function on free web hosting. The server can block your script and prevent it from working properly.
The fsockopen() function is a standard cURL function and works with both PHP and Perl. It’s an essential function for any PHP script. PHP supports both Unix and Internet socket targets. Use stream_get_transports() to find out which types of sockets are supported. By default, sockets are opened in blocking mode. To switch to non-blocking mode, you need to call stream_set_blocking(). Also, PHP provides a stream-oriented API, which provides a rich set of options and a non-blocking connection.
Here is a small code snippet you can use in PHP check if port is open:
if($pf = @fsockopen($domain,$port, $err, $err_string, 1))
$result = true;
fclose($pf);
>
Hope you will find this useful.