Php open unix socket

fsockopen

Initiates a socket connection to the resource specified by hostname .

PHP supports targets in the Internet and Unix domains as described in List of Supported Socket Transports. A list of supported transports can also be retrieved using stream_get_transports() .

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking() .

The function stream_socket_client() is similar but provides a richer set of options, including non-blocking connection and the ability to provide a stream context.

Parameters

If OpenSSL support is installed, you may prefix the hostname with either ssl:// or tls:// to use an SSL or TLS client connection over TCP/IP to connect to the remote host.

The port number. This can be omitted and skipped with -1 for transports that do not use ports, such as unix://.

If provided, holds the system level error number that occurred in the system-level connect() call.

If the value returned in errno is 0 and the function returned FALSE , it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket.

The error message as a string.

The connection timeout, in seconds.

Note:

If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout() , as the timeout parameter to fsockopen() only applies while connecting the socket.

Return Values

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets() , fgetss() , fwrite() , fclose() , and feof() ). If the call fails, it will return FALSE

Errors/Exceptions

Throws E_WARNING if hostname is not a valid domain.

Examples

Example #1 fsockopen() Example

$fp = fsockopen ( «www.example.com» , 80 , $errno , $errstr , 30 );
if (! $fp ) echo » $errstr ( $errno )
\n» ;
> else $out = «GET / HTTP/1.1\r\n» ;
$out .= «Host: www.example.com\r\n» ;
$out .= «Connection: Close\r\n\r\n» ;
fwrite ( $fp , $out );
while (! feof ( $fp )) echo fgets ( $fp , 128 );
>
fclose ( $fp );
>
?>

Example #2 Using UDP connection

The example below shows how to retrieve the day and time from the UDP service «daytime» (port 13) in your own machine.

$fp = fsockopen ( «udp://127.0.0.1» , 13 , $errno , $errstr );
if (! $fp ) echo «ERROR: $errno — $errstr
\n» ;
> else fwrite ( $fp , «\n» );
echo fread ( $fp , 26 );
fclose ( $fp );
>
?>

Notes

Note:

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a «connectionless» protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Note: When specifying a numerical IPv6 address (e.g. fe80::1), you must enclose the IP in square brackets—for example, tcp://[fe80::1]:80.

See Also

  • pfsockopen() — Open persistent Internet or Unix domain socket connection
  • stream_socket_client() — Open Internet or Unix domain socket connection
  • stream_set_blocking() — Set blocking/non-blocking mode on a stream
  • stream_set_timeout() — Set timeout period on a stream
  • fgets() — Gets line from file pointer
  • fgetss() — Gets line from file pointer and strip HTML tags
  • fwrite() — Binary-safe file write
  • fclose() — Closes an open file pointer
  • feof() — Tests for end-of-file on a file pointer
  • socket_connect() — Initiates a connection on a socket
  • The Curl extension

Источник

fsockopen

Устанавливает соединение с сокетом ресурса hostname .

PHP поддерживает целевые ресурсы в интернете и Unix доменах в том виде, как они описаны в Список поддерживаемых транспортных протоколов. Список поддерживаемых транспортов можно получить с помощью функции stream_get_transports() .

По умолчанию, сокет будет открыт в блокирующем режиме. Переключить его в неблокирующих режим можно функцией stream_set_blocking() .

stream_socket_client() выполняет аналогичную функцию, но предоставляет более широкий выбор настроек соединения, включающий установку неблокирующего режима и возможность предоставления потокового контекста.

Список параметров

Если установлена поддержка OpenSSL, можно использовать SSL или TLS протоколы соединений поверх TCP/IP при подключении к удаленному хосту. Для этого перед hostname нужно добавить префикс ssl:// или tls://.

Номер порта. Его можно не указывать, передав -1 для тех протоколов, которые не используют порты, например unix://.

Если этот параметр предоставить, то в случае ошибки системного вызова функции connect() он будет принимать номер этой ошибки.

Если значение параметра errno равно 0, а функция вернула FALSE , значит ошибка произошла до вызова connect(). В большинстве случаев это свидетельствует о проблемах при инициализации сокета.

Сообщение об ошибке в виде строки.

Таймаут соединения в секундах.

Замечание:

Если требуется установить таймаут чтения/записи данных через сокет, используйте функцию stream_set_timeout() , так как параметр timeout функции fsockopen() ограничивает только время процесса установки соединения с сокетом.

Возвращаемые значения

fsockopen() возвращает файловый указатель, который можно передавать в функции работающие с файлами (такие как fgets() , fgetss() , fwrite() , fclose() и feof() ). Если вызов завершится неудачей, функция вернет FALSE .

Ошибки

Вызывает ошибку уровня E_WARNING , если hostname не является допустимым доменом.

Примеры

Пример #1 Пример использования fsockopen()

$fp = fsockopen ( «www.example.com» , 80 , $errno , $errstr , 30 );
if (! $fp ) echo » $errstr ( $errno )
\n» ;
> else $out = «GET / HTTP/1.1\r\n» ;
$out .= «Host: www.example.com\r\n» ;
$out .= «Connection: Close\r\n\r\n» ;
fwrite ( $fp , $out );
while (! feof ( $fp )) echo fgets ( $fp , 128 );
>
fclose ( $fp );
>
?>

Пример #2 Использование UDP соединения

Пример ниже демонстрирует, как получить день и время от UDP службы «daytime» (порт 13) на вашей машине.

$fp = fsockopen ( «udp://127.0.0.1» , 13 , $errno , $errstr );
if (! $fp ) echo «ERROR: $errno — $errstr
\n» ;
> else fwrite ( $fp , «\n» );
echo fread ( $fp , 26 );
fclose ( $fp );
>
?>

Примечания

Замечание:

В зависимости от окружения, Unix домен или таймаут установки подключения могут оказаться недоступными.

Иногда UDP сокеты получают статус открытых, даже если удаленный хост недоступен. Ошибка проявит себя только во время чтения или записи данных в/из этого сокета. Причиной этому служит тот факт, что протокол UDP передает данные без установки соединения. То есть операционная система не устанавливает и не держит соединение с сокетом, пока не начнется передача данных.

Замечание: При указании числового адреса IPv6 (например, fe80::1) вы должны заключать его в квадратные скобки. Например, tcp://[fe80::1]:80.

Смотрите также

  • pfsockopen() — Открывает постоянное соединение с Интернет или сокетом Unix домена
  • stream_socket_client() — Открывает соединение с интернет-сокетом или с доменным сокетом Unix
  • stream_set_blocking() — Устанавливает блокирующий/неблокирующий режим на потоке
  • stream_set_timeout() — Устанавливает значение тайм-аута на потоке
  • fgets() — Читает строку из файла
  • fgetss() — Прочитать строку из файла и отбросить HTML-теги
  • fwrite() — Бинарно-безопасная запись в файл
  • fclose() — Закрывает открытый дескриптор файла
  • feof() — Проверяет, достигнут ли конец файла
  • socket_connect() — Начинает соединение с сокетом
  • Расширение Curl

Источник

fsockopen

Initiates a socket connection to the resource specified by hostname .

PHP supports targets in the Internet and Unix domains as described in List of Supported Socket Transports. A list of supported transports can also be retrieved using stream_get_transports().

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

The function stream_socket_client() is similar but provides a richer set of options, including non-blocking connection and the ability to provide a stream context.

Parameters

If OpenSSL support is installed, you may prefix the hostname with either ssl:// or tls:// to use an SSL or TLS client connection over TCP/IP to connect to the remote host.

The port number. This can be omitted and skipped with -1 for transports that do not use ports, such as unix:// .

If provided, holds the system level error number that occurred in the system-level connect() call.

If the value returned in error_code is 0 and the function returned false , it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket.

The error message as a string.

The connection timeout, in seconds. When null , the default_socket_timeout php.ini setting is used.

Note:

If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to fsockopen() only applies while connecting the socket.

Return Values

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()). If the call fails, it will return false

Errors/Exceptions

Throws E_WARNING if hostname is not a valid domain.

Changelog

Examples

Example #1 fsockopen() Example

 $fp = fsockopen("www.example.com", 80, $errno, $errstr, 30); if (!$fp) < echo "$errstr ($errno)
\n"
; > else < $out = "GET / HTTP/1.1\r\n"; $out .= "Host: www.example.com\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) < echo fgets($fp, 128); > fclose($fp); > ?>

Example #2 Using UDP connection

The example below shows how to retrieve the day and time from the UDP service «daytime» (port 13) in your own machine.

 $fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr); if (!$fp) < echo "ERROR: $errno - $errstr
\n"
; > else < fwrite($fp, "\n"); echo fread($fp, 26); fclose($fp); > ?>

Notes

Note:

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a «connectionless» protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Note: When specifying a numerical IPv6 address (e.g. fe80::1 ), you must enclose the IP in square brackets—for example, tcp://[fe80::1]:80 .

See Also

  • pfsockopen() — Open persistent Internet or Unix domain socket connection
  • stream_socket_client() — Open Internet or Unix domain socket connection
  • stream_set_blocking() — Set blocking/non-blocking mode on a stream
  • stream_set_timeout() — Set timeout period on a stream
  • fgets() — Gets line from file pointer
  • fgetss() — Gets line from file pointer and strip HTML tags
  • fwrite() — Binary-safe file write
  • fclose() — Closes an open file pointer
  • feof() — Tests for end-of-file on a file pointer
  • socket_connect() — Initiates a connection on a socket
  • The Curl extension
PHP 8.2

(PHP 4 4.0.1, 5, 7, 8) fscanf Parses input from file according to format The function fscanf() is similar to sscanf(), but it takes its input from file

(PHP 4, 5, 7, 8) fseek Seeks on a file pointer Sets the file position indicator for referenced by stream.

(PHP 4, 5, 7, 8) fstat Gets information about file using an open pointer Gathers statistics of file opened by pointer stream.

(PHP 8 8.1.0) fsync Synchronizes changes to the file (including meta-data) This function synchronizes changes to the file, including its meta-data.

Источник

Читайте также:  Monty python holy grail script
Оцените статью