function http_request($host, $data) { if (!($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { echo "socket_create() error!\r\n"; exit; } if (!socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, 1)) { echo "socket_set_option() error!\r\n"; exit; } if (!socket_connect($socket, $host, 80)) { echo "socket_connect() error!\r\n"; exit; } if (!socket_write($socket, $data, strlen($data))) { echo "socket_write() errror!\r\n"; exit; } while ($get = socket_read($socket, 1024, PHP_NORMAL_READ)) { $content .= $get; } socket_close($socket); $array = array('HTTP/1.1 404 Not Found', 'HTTP/1.1 300 Multiple Choices', 'HTTP/1.1 301 Moved Permanently', 'HTTP/1.1 302 Found', 'HTTP/1.1 304 Not Modified', 'HTTP/1.1 400 Bad Request', 'HTTP/1.1 401 Unauthorized', 'HTTP/1.1 402 Payment Required', 'HTTP/1.1 403 Forbidden', 'HTTP/1.1 405 Method Not Allowed', 'HTTP/1.1 406 Not Acceptable', 'HTTP/1.1 407 Proxy Authentication Required', 'HTTP/1.1 408 Request Timeout', 'HTTP/1.1 409 Conflict', 'HTTP/1.1 410 Gone', 'HTTP/1.1 411 Length Required', 'HTTP/1.1 412 Precondition Failed', 'HTTP/1.1 413 Request Entity Too Large', 'HTTP/1.1 414 Request-URI Too Long', 'HTTP/1.1 415 Unsupported Media Type', 'HTTP/1.1 416 Request Range Not Satisfiable', 'HTTP/1.1 417 Expectation Failed', 'HTTP/1.1 Retry With'); for ($i = 0; $i <= count($array); $i++) { if (eregi($array[$i], $content)) { return "{$array[$i]}\r\n"; break; } else { return "{$content}\r\n"; break; } } }
/** * Connects the TCP socket to the host with the given IP address and port * number * * Depending on whether PHP's sockets extension is loaded, this uses either * <var>socket_create</var>/<var>socket_connect</var> or * <var>fsockopen</var>. * * @param string $ipAddress The IP address to connect to * @param int $portNumber The TCP port to connect to * @param int $timeout The timeout in milliseconds * @throws SocketException if an error occurs during connecting the socket */ public function connect($ipAddress, $portNumber, $timeout) { $this->ipAddress = $ipAddress; $this->portNumber = $portNumber; if ($this->socketsEnabled) { if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { throw new SocketException(socket_last_error($this->socket)); } socket_set_nonblock($this->socket); @socket_connect($this->socket, $ipAddress, $portNumber); $write = array($this->socket); $read = $except = array(); $sec = floor($timeout / 1000); $usec = $timeout % 1000; if (!socket_select($read, $write, $except, $sec, $usec)) { $errorCode = socket_last_error($this->socket); } else { $errorCode = socket_get_option($this->socket, SOL_SOCKET, SO_ERROR); } if ($errorCode) { throw new SocketException($errorCode); } socket_set_block($this->socket); } else { if (!($this->socket = @fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, $timeout / 1000))) { throw new SocketException($socketErrstr); } stream_set_blocking($this->socket, true); } }
/** * {@inheritdoc} */ public function flushAll() { if ($this->currentOnly) { return apc_clear_cache('user') && apc_clear_cache(); } $result = true; foreach ($this->servers as $server) { if (count(explode('.', $server['ip'])) == 3) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } else { $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } // generate the raw http request $command = sprintf("GET %s HTTP/1.1\r\n", $this->getUrl()); $command .= sprintf("Host: %s\r\n", $server['domain']); if ($server['basic']) { $command .= sprintf("Authorization: Basic %s\r\n", $server['basic']); } $command .= "Connection: Close\r\n\r\n"; // setup the default timeout (avoid max execution time) socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0)); socket_connect($socket, $server['ip'], $server['port']); socket_write($socket, $command); $content = ''; do { $buffer = socket_read($socket, 1024); $content .= $buffer; } while (!empty($buffer)); if ($result) { $result = substr($content, -2) == 'ok'; } } return $result; }
function SendMail($email, $subject, $text) { $address = 'mail.iptm.ru'; // адрес smtp-сервера $port = 25; // порт (стандартный smtp - 25) // $from = '=?utf-8?b?' . base64_encode('Конференция «Рентгеновская оптика»') . '?= <*****@*****.**>'; // адрес отправителя $from = '*****@*****.**'; // адрес отправителя try { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // Создаем сокет if ($socket < 0) { throw new Exception('socket_create() failed: ' . socket_strerror(socket_last_error()) . "\n"); } $result = socket_connect($socket, $address, $port); // Соединяем сокет к серверу if ($result === false) { throw new Exception('socket_connect() failed: ' . socket_strerror(socket_last_error()) . "\n"); } read_smtp_answer($socket); // Читаем информацию о сервере write_smtp_response($socket, 'EHLO ' . $_SERVER['SERVER_NAME']); // Приветствуем сервер read_smtp_answer($socket); // ответ сервера write_smtp_response($socket, 'MAIL FROM:<' . $from . '> BODY=8BITMIME'); // Задаем адрес отправителя read_smtp_answer($socket); // ответ сервера write_smtp_response($socket, 'RCPT TO:<' . $email . '>'); // Задаем адрес получателя read_smtp_answer($socket); // ответ сервера write_smtp_response($socket, 'DATA'); // Готовим сервер к приему данных read_smtp_answer($socket); // ответ сервера $header = "From: " . $from . "\r\n"; $header .= "To: " . $email . "\r\n"; $header .= "Subject: =?utf-8?b?" . base64_encode($subject) . "?=\r\n"; $header .= "Content-Type: text/plain; charset=\"utf-8\"\r\n"; $header .= "Content-Transfer-Encoding: base64\r\n"; $header .= "Mime-Version: 1.0\r\n"; $text = $header . base64_encode($text); write_smtp_response($socket, $text . "\r\n."); // Отправляем данные read_smtp_answer($socket); // ответ сервера write_smtp_response($socket, 'QUIT'); // Отсоединяемся от сервера read_smtp_answer($socket); // ответ сервера } catch (Exception $e) { echo "\nError: " . $e->getMessage(); } if (isset($socket)) { socket_close($socket); } }
function getsock($addr, $port) { $socket = null; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false || $socket === null) { $error = socket_strerror(socket_last_error()); $msg = "socket create(TCP) failed"; echo "ERR: {$msg} '{$error}'\n"; return null; } $res = socket_connect($socket, $addr, $port); if ($res === false) { $error = socket_strerror(socket_last_error()); $msg = '<center class="alert alert-danger bs-alert-old-docs">CGMiner is not running...If it is not restart after minutes ,please try to reboot.</center>'; socket_close($socket); echo $msg; @exec('sudo service cgminer stop '); @exec('sudo service cgminer stop '); @exec('sudo service cgminer stop '); $network = get_network(); $gateway = $network['gateway_id']; @exec('sudo route add default gw ' . $gateway); //sleep(3); //@exec('sudo service cgminer start &'); //showmsg($msg,'?c=home&m=reboot','10000'); //echo "ERR: $msg '$error'\n"; //exit; return null; } return $socket; }
function pole_display_price($label, $price) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (@socket_connect($sock, '127.0.0.1', 1888)) { socket_write($sock, sprintf("\r\n%-19.19s\n\r\$%18.2f ", $label, $price)); } }
public function connect($address = "", $port = "") { global $merchantAddress; if ($this->connected) { $this->close(); } $a = Tools::address($merchantAddress); if (empty($port) || !is_integer($port)) { $port = intval($a['port']); } if (empty($address)) { $address = $a['address']; } $address = gethostbyname($address); $this->address = $address; $this->port = $port; $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->socket === false) { return false; } $result = socket_connect($this->socket, $this->address, $this->port); if ($result === false) { return false; } $this->connectmessage = @socket_read($this->socket, 1024 * 1024, PHP_NORMAL_READ); $this->connected = true; return true; }
/** * Connects a socket to an external host and port * @param string $ip_address * @return boolean */ static function connectSocket($sock, $host, $port, &$connect_error = '', $socket_timeout = 5) { $attempts = 0; socket_set_block($sock); while (!($connected = @socket_connect($sock, $host, $port)) && $attempts++ < $socket_timeout) { $sock_error = socket_last_error(); if ($sock_error != SOCKET_EINPROGRESS && $sock_error != SOCKET_EALREADY) { $connect_error = socket_strerror($sock_error); return false; } sleep(125); } $connect_buffer = ''; $attempts = 0; while (!($connect_buffer = @socket_read($sock, 4096, PHP_BINARY_READ)) && $attempts++ < $socket_timeout) { $sock_error = socket_last_error(); if ($sock_error != SOCKET_EINPROGRESS && $sock_error != SOCKET_EALREADY && $sock_error != SOCKET_EAGAIN) { $connect_buffer .= socket_strerror($sock_error); return false; } usleep(125); } if (!$connected) { $connect_error = socket_strerror($sock_error); return false; } return $connect_buffer; }
public function connect() { $this->socketCon = socket_connect($this->socketVar, $this->ip, $this->port); if (!$this->socketCon) { die("Cannot Connnect: Exiting With Exception : " . socket_strerror(socket_last_error()) . PHP_EOL); } }
public function __construct($host, $port) { $ipAddr = self::DEFAULT_IPADDR; if (false === ip2long($host)) { $ipAddr = gethostbyname($host); } else { $ipAddr = $host; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (false === $socket) { throw new PhpBuf_RPC_Socket_Exception('socket creation fail:' . socket_strerror(socket_last_error())); } $connected = socket_connect($socket, $ipAddr, $port); if (false === $connected) { throw new PhpBuf_RPC_Socket_Exception('socket connection fail:' . socket_strerror(socket_last_error())); } socket_set_nonblock($socket); // socket_set_timeout($socket, 5); socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 1)); socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); if (defined('TCP_NODELAY')) { socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1); } $this->socket = $socket; }
protected function connect($host, $port) { $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); set_error_handler(__CLASS__ . '::handleError'); $this->isAvailable = socket_connect($this->socket, $host, $port); restore_error_handler(); }
private static function _tcp_send_request($socket_write_json = null) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (false === $sock) { echo "sock create error!\n"; } $address = Config::get("kgi.kgi_mid_server_ip"); $port = Config::get("kgi.kgi_mid_server_port"); try { $result = socket_connect($sock, $address, $port); if ($result === false) { echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($sock)) . "\n"; exit; die; } socket_write($sock, $socket_write_json, strlen($socket_write_json)); while ($out_str = socket_read($sock, 2048)) { // echo "revice result\n"; // echo $out_str . "\n"; $json_data = json_decode($out_str); break; } socket_close($sock); } catch (\ErrorException $e) { //echo $e->getMessage() . "\n"; } }
/** * Gets the OrientSocket, and establishes the connection if required. * * @return \PhpOrient\Protocols\Binary\OrientSocket * * @throws SocketException * @throws PhpOrientWrongProtocolVersionException */ public function connect() { if (!$this->connected) { if (empty($this->hostname) && empty($this->port)) { throw new SocketException('Can not initialize a connection ' . 'without connection parameters'); } if (!extension_loaded("sockets")) { throw new SocketException('Can not initialize a connection ' . 'without socket extension enabled. Please check you php.ini'); } $this->_socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_set_block($this->_socket); socket_set_option($this->_socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => self::READ_TIMEOUT, 'usec' => 0)); socket_set_option($this->_socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => self::WRITE_TIMEOUT, 'usec' => 0)); $x = @socket_connect($this->_socket, $this->hostname, $this->port); if (!is_resource($this->_socket) || $x === false) { throw new SocketException($this->getErr() . PHP_EOL); } $protocol = Reader::unpackShort($this->read(2)); if ($protocol > $this->protocolVersion) { throw new PhpOrientWrongProtocolVersionException('Protocol version ' . $protocol . ' is not supported.'); } //protocol handshake $this->protocolVersion = $protocol; $this->connected = true; } return $this; }
/** * Send message package to the socket server * Basic layer method * * @return mixed */ public function send($msg, $is_block = false) { if (!$this->host || !$this->port) { throw new Hush_Socket_Exception("Please set server's host and port first"); } /* Create a TCP/IP socket. */ $this->sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->sock < 0) { echo "socket_create() failed.\nReason: " . socket_strerror($this->sock) . "\n"; } $result = @socket_connect($this->sock, $this->host, $this->port); if ($result < 0) { echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n"; } if ($is_block) { @socket_set_nonblock($this->sock); } // add suffix for socket msg $msg = trim($msg) . "\r\n"; @socket_write($this->sock, $msg, strlen($msg)); $result = @socket_read($this->sock, 2048); // unserialize data from socket server $result = unserialize(trim($result)); return $result; }
/** * Connects the TCP socket to the host with the given IP address and port number */ public function connect(InetAddress $ipAddress, $portNumber) { $this->ipAddress = $ipAddress; $this->portNumber = $portNumber; if ($this->socketsEnabled) { if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { $errorCode = socket_last_error($this->socket); throw new Exception("Could not create socket: " . socket_strerror($errorCode)); } if (@(!socket_connect($this->socket, $ipAddress, $portNumber))) { $errorCode = socket_last_error($this->socket); throw new Exception("Could not connect socket: " . socket_strerror($errorCode)); } if ($this->isBlocking) { socket_set_block($this->socket); } else { socket_set_nonblock($this->socket); } } else { if (!($this->socket = fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, 2))) { throw new Exception("Could not create socket."); } stream_set_blocking($this->socket, $this->isBlocking); } }
public function flushAll() { $result = true; foreach ($this->servers as $server) { if (count(explode('.', $server['ip']) == 3)) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } else { $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } // generate the raw http request $command = sprintf("GET %s HTTP/1.1\r\n", $this->router->generate('sonata_page_apc_cache', array('token' => $this->token))); $command .= sprintf("Host: %s\r\n", $server['domain']); $command .= "Connection: Close\r\n\r\n"; // setup the default timeout (avoid max execution time) socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0)); socket_connect($socket, $server['ip'], $server['port']); socket_write($socket, $command); $content = socket_read($socket, 1024); if ($result) { $result = substr($content, -2) == 'ok' ? true : false; } } return $result; }
public function index() { error_reporting(E_ALL); set_time_limit(0); $service_port = 6005; $address = "203.130.45.233"; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket < 0) { echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n"; } $result = socket_connect($socket, $address, $service_port); if ($result < 0) { echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n"; } else { echo "连接OK<br>"; } $in = "1!"; //1!是发给这个设备的指令 $out = ''; $out1 = ''; if (!socket_write($socket, $in, strlen($in))) { echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n"; } while ($out = socket_read($socket, 8192)) { //$out=trim($out,"0xff"); //$out=trim($out,"0x00"); //$this->xieru($out,"sj"); echo $out; } socket_close($socket); }
function coop_send($message) { if (!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [{$errorcode}] {$errormsg} \n"); } //Connect socket to remote server if (!socket_connect($sock, COOPSERVER, COOPPORT)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not connect: [{$errorcode}] {$errormsg} \n"); } //Send the message to the server if (!socket_send($sock, $message, strlen($message), 0)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not send data: [{$errorcode}] {$errormsg} \n"); } $buf = 'my buffer'; if (false !== ($bytes = socket_recv($sock, $buf, 1024, 0))) { echo "Read {$bytes} bytes of socket_recv(). close socket ..."; } else { echo "socket_recv() error; Reason: " . socket_strerror(socket_last_error($socket)) . "\n"; } socket_close($sock); return $buf; }
function sendsock($in) { global $config; $service_port = $config['sockport']; $address = $config['sockhost']; if (!function_exists("socket_create")) { error_log(date("y-m-d H:i:s") . " 未启用socket模块\n", 3, "error.log"); return null; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { error_log(date("y-m-d H:i:s") . "socket_create() failed, reason: " . socket_strerror(socket_last_error()) . "\n", 3, "error.log"); return null; } $result = socket_connect($socket, $address, $service_port); if ($result === false) { error_log(date("y-m-d H:i:s") . "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($socket)) . "\n", 3, "error.log"); return null; } socket_write($socket, $in, strlen($in)); $result = socket_read($socket, 8192); $arr = unpack("C*", $result); socket_close($socket); return $arr; }
function refresh_user($discord_id) { global $socket, $error; $so = socket_create(AF_UNIX, SOCK_DGRAM, 0); if ($so === false) { $msg = socket_strerror(socket_last_error()); $error = "Socket failed: {$msg}"; } else { $res = socket_connect($so, $socket); if ($res === false) { $msg = socket_strerror(socket_last_error()); $error = "Connect failed: {$msg}"; } else { $payload = json_encode(array('action' => 'refresh', 'user_id' => $discord_id)); $res = socket_write($so, $payload); if ($res === false) { $error = "Socket send failed"; } else { if ($res < strlen($payload)) { $error = "Socket did not send all data"; } } socket_shutdown($so); socket_close($so); } } }
/** * Open a socket if there isn't one open already, return it. * Returns false on error. * * @return false|resource */ protected function getSocket() { if ($this->socket !== null) { return $this->socket; } $ip = $this->getIP(); if (!$ip) { $this->log("DNS error"); $this->markDown(); return false; } $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_nonblock($this->socket); wfSuppressWarnings(); $ok = socket_connect($this->socket, $ip, $this->port); wfRestoreWarnings(); if (!$ok) { $error = socket_last_error($this->socket); if ($error !== self::EINPROGRESS) { $this->log("connection error: " . socket_strerror($error)); $this->markDown(); return false; } } return $this->socket; }
/** * 连接到服务器 * 接受一个浮点型数字作为超时,整数部分作为sec,小数部分*100万作为usec * * @param string $host 服务器地址 * @param int $port 服务器地址 * @param float $timeout 超时默认值,连接,发送,接收都使用此设置 * @param bool $udp_connect 是否启用connect方式 */ function connect($host, $port, $timeout = 0.1, $udp_connect = true) { //判断超时为0或负数 if (empty($host) or empty($port) or $timeout <= 0) { $this->errCode = -10001; $this->errMsg = "param error"; return false; } $this->host = $host; $this->port = $port; $this->sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); $this->set_timeout($timeout, $timeout); //$this->set_bufsize($this->sendbuf_size, $this->recvbuf_size); //是否用UDP Connect if ($udp_connect !== true) { return true; } if (socket_connect($this->sock, $host, $port)) { //清理connect前的buffer数据遗留 while (@socket_recv($this->sock, $buf, 65535, MSG_DONTWAIT)) { } return true; } else { $this->set_error(); return false; } }
function ircReport($stuff) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port")); socket_write($sock, $stuff . "\n"); socket_close($sock); }
/** * Connect the socket to the address specified in the options * * @return Socket the current object, for chaning */ public function connect() { if (!socket_connect($this->socket, $this->options['address'], $this->options['port'])) { throw new SocketException(); } return $this; }
function getsock($port) { $socket = null; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false || $socket === null) { $error = socket_strerror(socket_last_error()); $msg = "socket create({$port}) failed"; echo "ERR: {$msg} '{$error}'\n"; return NULL; } socket_set_nonblock($socket); $res = socket_connect($socket, API_HOST, $port); $timeout = 50; while ($res === false && $timeout > 0) { $err = socket_last_error($socket); echo "."; if ($timeout > 1 && ($err == 115 || $err == 114)) { $timeout--; usleep(50); $res = socket_connect($socket, API_HOST, $port); continue; } $error = socket_strerror($err); $msg = "socket connect({$port}) failed"; echo "ERR: {$msg} '{$error}'\n"; socket_close($socket); return NULL; } socket_set_block($socket); return $socket; }
protected function connectSocket() { if (filter_var($this->host, FILTER_VALIDATE_IP)) { $ip = $this->host; } else { $ip = gethostbyname($this->host); if ($ip == $this->host) { throw new MongoConnectionException(sprintf('couldn\'t get host info for %s', $this->host)); } } // For some reason, PHP doesn't currently allow resources opened with // fsockopen/pfsockopen to be used with socket_* functions, but HHVM does. if (defined('HHVM_VERSION')) { $this->socket = pfsockopen($ip, $this->port, $errno, $errstr, $this->connectTimeoutMS / 1000); if ($this->socket === false) { $this->socket = null; throw new MongoConnectionException(sprintf("unable to connect to {$ip}:{$this->port} because: %s", "{$errstr} ({$errno})")); } } else { $this->socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp")); if (!$this->socket) { throw new MongoConnectionException(sprintf('error creating socket: %s', socket_strerror(socket_last_error()))); } $connected = socket_connect($this->socket, $ip, $this->port); if (!$connected) { throw new MongoConnectionException(sprintf("unable to connect to {$ip}:{$this->port} because: %s", socket_strerror(socket_last_error()))); } } }
function hg_sendCmd($cmd, $ip, $port) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket < 0) { return false; } $result = socket_connect($socket, $ip, $port); if ($result < 0) { return false; } if (!isset($cmd['charset'])) { $cmd['charset'] = ''; } $str = json_encode($cmd); //echo ($str); //$str = base64_encode($str); socket_write($socket, $str, strlen($str)); $data = ''; while ($out = socket_read($socket, 256)) { $data .= $out; if (strlen($out) < 256) { break; } } socket_close($socket); //$data = base64_decode($data); return $data; }
function Ping($dst_addr, $timeout = 5, $percision = 3) { // lets catch dumb people if ((int) $timeout <= 0) { $timeout = 5; } if ((int) $percision <= 0) { $percision = 3; } // set the timeout socket_set_option($this->icmp_socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $timeout, "usec" => 0)); if ($dst_addr) { if (@socket_connect($this->icmp_socket, $dst_addr, NULL)) { } else { $this->errstr = "Cannot connect to {$dst_addr}"; return FALSE; } $this->Build_Packet(); $this->start_time(); socket_write($this->icmp_socket, $this->request, $this->request_len); if (@socket_recv($this->icmp_socket, &$this->reply, 256, 0)) { $this->time = $this->get_time($percision); return $this->time; } else { $this->errstr = "Timed out"; return FALSE; } } else { $this->errstr = "Destination address not specified"; return FALSE; } }
/** * send summary to graphite * @return bool - status of operation (TRUE = success, FALSE = failure) */ public function sendAll() { $bucket_prefix = $this->buildBucketPrefix(); $address = gethostbyname($this->cfg['host']); $cmdBuf = ''; foreach ($this->stats_summary as $stat) { // action name mapping $action = preg_replace('/[\\. ]/', '', $stat['action']); $action = preg_replace('/_ACTION$/', '', $action); // HACK to prevent old event names to appear in graphite if (!preg_match('/_/', $action)) { continue; } $cmdBuf .= $bucket_prefix . $action . ' ' . $stat['value'] . ' ' . $stat['time'] . "\n"; } // var_dump($cmdBuf); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $result = socket_connect($socket, $address, $this->cfg['port']); if (!$result) { return false; } $write_result = socket_write($socket, $cmdBuf, strlen($cmdBuf)); if (!$write_result) { return false; } return true; }
function sendUSD($text, $pass_server = '000000') { $address = gethostbyname('127.0.0.1'); //IP Адрес вашего компьютера $service_port = 8000; //Порт //$pass_server='000000'; //Пароль $phone = preg_replace('/^\\+/', '', $phone); $socket = socket_create(AF_INET, SOCK_STREAM, 0); if ($socket < 0) { echo "socket create failed reason: " . socket_strerror($socket) . "\n"; } $result = socket_connect($socket, $address, $service_port); if ($result < 0) { echo "socket connect failed.\nReason: ({$result}) " . socket_strerror($result) . "\n"; } $text = iconv("UTF-8", "Windows-1251", $text); $in = base64_encode($pass_server . "#CMD#[USSD]" . $text); //Пример отправки смс //$in = base64_encode($pass_server."#CMD#[USSD]*102#"); //Пример запроса USSD команды $out = ''; socket_write($socket, $in, strlen($in)); //echo "Response:\n\n"; $res = ''; while ($out = socket_read($socket, 2048)) { $res .= $out; } socket_close($socket); $res = iconv("Windows-1251", "UTF-8", $res); if (preg_match('/USSD-RESPONSE\\[.+?\\]:(.+)/is', $res, $m)) { $res = $m[1]; } return $res; }