Php socket_set_option
This tutorials show you how to use socket_set_option.
The socket_set_option is declared as follows:
socket_set_option( Socket $socket, int $level, int $option, array|string|int $value ): bool
The return value is Returns true on success or false on failure.
Examples
The following code shows how to use socket_set_option.
/* w w w . de m o 2 s . c o m */ function is_online_for_inventory($ip)< if (ifPingable($ip, $timeout = 1) != false) < # code. return "Online"; >else< return "Offline"; > > function ifPingable($host, $timeout = 1) < /* ICMP ping packet with a pre-calculated checksum */ $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost"; $socket = socket_create(AF_INET, SOCK_RAW, 1); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0)); socket_connect($socket, $host, null); $ts = microtime(true); socket_send($socket, $package, strLen($package), 0); if (socket_read($socket, 255)) $result = microtime(true) - $ts; else $result = false; socket_close($socket); return $result; > ?>
/*w w w. d e m o 2 s . c o m */ namespace Tracker; class UdpHandler < private $stream = null; private $socket = null; private $host = null; private $port = null; public function __construct($host = '127.0.0.1' , $port = 1223) < $this->host = $host; $this->port = $port; $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_set_option($this->socket, SOL_SOCKET, SO_SNDTIMEO, ["sec" => 1, "usec" => 0]); socket_set_nonblock($this->socket); if(!$this->socket) < throw new \Exception('Unable to open stream'); > > public function send($data) < if(!$this->socket) < throw new \Exception('Stream not opened'); > socket_sendto($this->socket, $data, strlen($data), 0, $this->host, $this->port); return true; > >
// w w w . de m o 2s . c om function wol($broadcast, $mac) < $mac_array = split(':', $mac); $hwaddr = ''; foreach($mac_array AS $octet) < $hwaddr .= chr(hexdec($octet)); >// Create Magic Packet $packet = ''; for ($i = 1; $i for ($i = 1; $i $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if ($sock) < $options = socket_set_option($sock, 1, 6, true); if ($options >=0) < $e = socket_sendto($sock, $packet, strlen($packet), 0, $broadcast, 9); socket_close($sock); echo "STUFF!"; echo $packet; echo $broadcast; > > > wol("24.241.224.117","00:1F:BC:02:47:2D"); ?>
/*w w w . d e m o 2s . c o m*/ class Socket < private $_socket = NULL; private $_address = '127.0.0.1'; private $_port = 8001; private $_connected = false; public function __construct($address, $port) < $this->_address = $address; $this->_port = $port; > private function create() < $this->_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die('socket_create failed.'); socket_set_option($this->_socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0)); > private function connect() < if (!$this->_socket) $this->create(); socket_connect($this->_socket, $this->_address, $this->_port) or die('socket_connect failed.'); $this->_connected = true; > public function write($content) < if (!$this->_connected) $this->connect(); socket_write($this->_socket, $content, strlen($content)); $buf = socket_read($this->_socket, 2048); return $buf; > public function __destruct() < socket_close($this->_socket); > >
// w w w . de m o 2s . c o m echo ifPingable("8.8.8.8"); echo "
"; $ip = "69.70.200.246"; $comm="public"; $oid=".1.3.6.1.2.1.1.1.0"; echo snmpget_generic($ip, $comm, $oid); function ifPingable($host, $timeout = 3) < /* ICMP ping packet with a pre-calculated checksum */ $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost"; $socket = socket_create(AF_INET, SOCK_RAW, 1); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0)); socket_connect($socket, $host, null); $ts = microtime(true); socket_send($socket, $package, strLen($package), 0); if (socket_read($socket, 255)) $result = microtime(true) - $ts; else $result = false; socket_close($socket); return $result; > function snmpget_generic($ip, $comm, $oid) < $command = "C:\usr\bin\snmpget -Ov -v 1 -c " . $comm . " " . $ip . " " . $oid . " 2>&1"; $result = shell_exec ( $command ); $result = ext ( $result ); $result = removeQuotation($result); return $result; > ?>
Related
demo2s.com | Email: | Demo Source and Support. All rights reserved.
socket_set_option
Функция socket_set_option() устанавливает опцию указанную в параметре option , на уровне протокола level , в значение, указанное параметром value для сокета socket .
Список параметров
Экземпляр Socket , созданный при помощи функции socket_create() или socket_accept() .
Параметр level указывает уровень протокола, на котором используется опция. Например, чтобы установить опции на уровне сокета, параметр level должен быть установлен в SOL_SOCKET . Другие уровни, такие как TCP, можно использовать, указав номер протокола этого уровня. Номер протоколов можно найти с помощью функции getprotobyname() .
Возможные опции для сокета те же самые, как и для функции socket_get_option() .
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
Примеры
Пример #1 Пример использования socket_set_option()
$socket = socket_create ( AF_INET , SOCK_STREAM , SOL_TCP );
?php
if (! is_resource ( $socket )) echo ‘Не могу создать сокет: ‘ . socket_strerror ( socket_last_error ()) . PHP_EOL ;
>
if (! socket_set_option ( $socket , SOL_SOCKET , SO_REUSEADDR , 1 )) echo ‘Не могу установить опцию на сокете: ‘ . socket_strerror ( socket_last_error ()) . PHP_EOL ;
>
if (! socket_bind ( $socket , ‘127.0.0.1’ , 1223 )) echo ‘Не могу привязать сокет: ‘ . socket_strerror ( socket_last_error ()) . PHP_EOL ;
>
$rval = socket_get_option ( $socket , SOL_SOCKET , SO_REUSEADDR );
if ( $rval === false ) echo ‘Не могу получить опцию сокета: ‘ . socket_strerror ( socket_last_error ()) . PHP_EOL ;
> else if ( $rval !== 0 ) echo ‘Опция SO_REUSEADDR установлена на сокете!’ . PHP_EOL ;
>
?>
Смотрите также
- socket_create() — Создаёт сокет (конечную точку для обмена информацией)
- socket_bind() — Привязывает имя к сокету
- socket_strerror() — Возвращает строку, описывающую ошибку сокета
- socket_last_error() — Возвращает последнюю ошибку на сокете
- socket_get_option() — Получает опции потока для сокета
User Contributed Notes 8 notes
To expand a bit more on what «tim at e2-media dot co dot nz» started.
SO_SNDTIMEO is one of the many constants you can use with socket_set_option.
See http://ca.php.net/manual/en/ref.sockets.php for the available Predefind Constants and visit http://man.he.net/man2/setsockopt for the meaning of the ones relevant.
Tim’s example might seem at first a bit non-intuitive since he is using the SO_SNDTIMEO constant. Which means, if the socket has to send out data, it must do it within the limit specified — in his case 10 seconds. Usually you won’t set a timeout for sending out data. Nevertheless, the example is valid, and there are situations where you need to do so.
A more intuitive use of socket_set_option would be to set a time out for a blocking socket (a socket that waits for data to be receive when read from). You would do this like so:
socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array(«sec»=>0, «usec»=>100));
Notice that sec= 0 and usec= 100; Depending on how long you want your program to wait to recieve data, you might want to change these values.
Lingering will sometimes not work when you’re working with non-blocking sockets. Even if the socket is set to linger and you keep tying to close until the socket doesn’t return an error and the resource is no longer identifiable as type ‘Socket’, the socket may STILL close without sending everything.
Therefore, in the event that you are using non-blocking sockets (which is preferable if you care at all about signaling), you should set the socket as blocking (socket_set_block()) before calling to close it. This will allow everything to flush before it returns.
PHP 7.3.6, and probably many previous versions, automatically sets SO_REUSEADDR when you use stream_socket_server().
#ifdef SO_REUSEADDR
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&sockoptval, sizeof(sockoptval));
#endif
I initially thought I’d need to play with context options to turn this on, but no, the simplest single-arg call with no error checking and just an address, works for me.
strace your PHP binary to be 100% sure:
.
setsockopt(3, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0
.
The chances are you ARE using SO_REUSEADDR unless you’re using a 100-year old UNIX clone in a month with a Z in it.
Why is the size of the buffer 2 times that set by me?
//Before setting the cache area
$sock = socket_create ( AF_INET , SOCK_STREAM , getprotobyname ( ‘tcp’ ));
socket_bind ( $sock , ‘127.0.0.1’ , 5000 );
socket_listen ( $sock , 1024 );
$sndbuf = socket_get_option ( $sock , SOL_SOCKET , SO_SNDBUF );
$rcvbuf = socket_get_option ( $sock , SOL_SOCKET , SO_RCVBUF );
printf ( «send buffer size(写缓存区大小):%sm \n» , $sndbuf / 1024 );
printf ( «receive buffer(读缓存区大小)%sm \n» , $rcvbuf / 1024 );
//After setting the cache area
$snd_buf = 1024 * 3 ;
$rcv_buf = 1024 * 3 ;
socket_set_option ( $sock , SOL_SOCKET , SO_SNDBUF , $snd_buf );
socket_set_option ( $sock , SOL_SOCKET , SO_RCVBUF , $rcv_buf );
$sndbuf = socket_get_option ( $sock , SOL_SOCKET , SO_SNDBUF );
$rcvbuf = socket_get_option ( $sock , SOL_SOCKET , SO_RCVBUF );
printf ( «send buffer size(写缓存区大小):%sm \n» , $sndbuf / 1024 );
printf ( «receive buffer size(读缓存区大小)%sm \n» , $rcvbuf / 1024 );
?>
I would like to comment on the previous note regarding blocking sockets.
There is more to blocking sockets than waiting for data to be received when trying to be read upon, just to make example, a listening blocking socket will wait for a client to try to connect before it returns when you socket_accept() it.
To set a socket timeout value (assuming you’ve set it blocking) use:
socket_set_option(
$socket,
SOL_SOCKET, // socket level
SO_SNDTIMEO, // timeout option
array(
«sec»=>10, // Timeout in seconds
«usec»=>0 // I assume timeout in microseconds
)
);
Setting the socket timeout microseconds (‘usec’) does not work under Windows, at least under PHP/5.2.9:
$timeout = array( ‘sec’ => 1 , ‘usec’ => 500000 );
socket_set_option ( $socket , SOL_SOCKET , SO_RCVTIMEO , $timeout );
var_dump ( socket_set_option ( $socket , SOL_SOCKET , SO_RCVTIMEO ));
- Функции сокета
- socket_accept
- socket_addrinfo_bind
- socket_addrinfo_connect
- socket_addrinfo_explain
- socket_addrinfo_lookup
- socket_bind
- socket_clear_error
- socket_close
- socket_cmsg_space
- socket_connect
- socket_create_listen
- socket_create_pair
- socket_create
- socket_export_stream
- socket_get_option
- socket_getopt
- socket_getpeername
- socket_getsockname
- socket_import_stream
- socket_last_error
- socket_listen
- socket_read
- socket_recv
- socket_recvfrom
- socket_recvmsg
- socket_select
- socket_send
- socket_sendmsg
- socket_sendto
- socket_set_block
- socket_set_nonblock
- socket_set_option
- socket_setopt
- socket_shutdown
- socket_strerror
- socket_write
- socket_wsaprotocol_info_export
- socket_wsaprotocol_info_import
- socket_wsaprotocol_info_release
socket_set_option
The socket_set_option() function sets the option specified by the optname parameter, at the specified protocol level , to the value pointed to by the optval parameter for the socket .
Список параметров
A valid socket resource created with socket_create() or socket_accept().
The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function.
The available socket options are the same as those for the socket_get_option() function.
Возвращаемые значения
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Примеры
Пример #1 socket_set_option() example
$socket = socket_create ( AF_INET , SOCK_STREAM , SOL_TCP );
if (! is_resource ( $socket )) echo ‘Unable to create socket: ‘ . socket_strerror ( socket_last_error ()) . PHP_EOL ;
>if (! socket_set_option ( $socket , SOL_SOCKET , SO_REUSEADDR , 1 )) echo ‘Unable to set option on socket: ‘ . socket_strerror ( socket_last_error ()) . PHP_EOL ;
>if (! socket_bind ( $socket , ‘127.0.0.1’ , 1223 )) echo ‘Unable to bind socket: ‘ . socket_strerror ( socket_last_error ()) . PHP_EOL ;
>$rval = socket_get_option ( $socket , SOL_SOCKET , SO_REUSEADDR );
if ( $rval === false ) echo ‘Unable to get socket option: ‘ . socket_strerror ( socket_last_error ()) . PHP_EOL ;
> else if ( $rval !== 0 ) echo ‘SO_REUSEADDR is set on socket !’ . PHP_EOL ;
>
?>Список изменений
Версия Описание 4.3.0 This function was renamed. It used to be called socket_setopt().