/** * 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); } }
public function create() { $socket = null; if (($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) { $errno = socket_last_error(); throw new RuntimeException('socket_create: ' . socket_strerror($errno), $errno); } $ret = socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); $ret = socket_get_option($socket, SOL_SOCKET, SO_KEEPALIVE); if ($ret === false) { $errno = socket_last_error($socket); throw new RuntimeException('socket_get_option SO_KEEPALIVE: ' . socket_strerror($errno), $errno); } $ret = socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); $ret = socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR); if ($ret === false) { $errno = socket_last_error($socket); throw new RuntimeException('socket_get_option SO_REUSEADDR: ' . socket_strerror($errno), $errno); } $ret = socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 5, 'usec' => 0)); $ret = socket_get_option($socket, SOL_SOCKET, SO_RCVTIMEO); if ($ret === false) { $errno = socket_last_error($socket); throw new RuntimeException('socket_get_option SO_RCVTIMEO: ' . socket_strerror($errno), $errno); } $ret = socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0)); $ret = socket_get_option($socket, SOL_SOCKET, SO_SNDTIMEO); if ($ret === false) { $errno = socket_last_error($socket); throw new RuntimeException('socket_get_option SO_SNDTIMEO: ' . socket_strerror($errno), $errno); } socket_set_nonblock($socket); return $socket; }
public function logMetadata() { $sendBuffer = socket_get_option($this->socket, SOL_SOCKET, SO_SNDBUF); $rcvBuffer = socket_get_option($this->socket, SOL_SOCKET, SO_RCVBUF); $linger = socket_get_option($this->socket, SOL_SOCKET, SO_LINGER); $keep = socket_get_option($this->socket, SOL_SOCKET, SO_KEEPALIVE); Gpf_Log::debug(var_export(array('send' => $sendBuffer, 'rcv' => $rcvBuffer, 'linger' => $linger, 'keepalive' => $keep), true)); }
function socket_onConnect($socket) { $err = socket_get_option($socket, SOL_SOCKET, SO_ERROR); if ($err == 0) { echo "connect server success\n"; swoole_event_set($socket, null, 'socket_onWrite', SWOOLE_EVENT_READ); socket_write($socket, "first package\n"); } else { echo "connect server failed\n"; swoole_event_del($socket); socket_close($socket); } }
public function scan($cb = null) { $this->createSockets(); $poll = microtime(true); while ($this->socks && microtime(true) - $poll < $this->timeout) { $null = null; $write = $this->socks; socket_select($null, $write, $null, 0, 50); $this->handleSelect($write, function ($sock) { return socket_get_option($sock, SOL_SOCKET, SO_ERROR); }); } $this->handleSelect($this->socks, function () { return SOCKET_ETIMEDOUT; }); }
function test($stream, $sock) { if ($stream !== null) { echo "stream_set_blocking "; print_r(stream_set_blocking($stream, 0)); echo "\n"; } if ($sock !== null) { echo "socket_set_block "; print_r(socket_set_block($sock)); echo "\n"; echo "socket_get_option "; print_r(socket_get_option($sock, SOL_SOCKET, SO_TYPE)); echo "\n"; } echo "\n"; }
/** * Initializes the network handler. */ public function register() { if (($this->sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { throw new StupidHttp_NetworkException("Can't create socket: " . socket_strerror(socket_last_error())); } if (@socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1) === false) { throw new StupidHttp_NetworkException("Can't set options on the socket: " . socket_strerror(socket_last_error())); } if (@socket_bind($this->sock, $this->address, $this->port) === false) { throw new StupidHttp_NetworkException("Can't bind socket to {$this->address}:{$this->port}: " . socket_strerror(socket_last_error($this->sock))); } if (@socket_listen($this->sock) === false) { throw new StupidHttp_NetworkException("Failed listening to socket on {$this->address}:{$this->port}: " . socket_strerror(socket_last_error($this->sock))); } $this->sockSendBufferSize = @socket_get_option($this->sock, SOL_SOCKET, SO_SNDBUF); $this->sockReceiveBufferSize = @socket_get_option($this->sock, SOL_SOCKET, SO_RCVBUF); }
/** * Creates the object that will deal with the socket. */ public function __construct($protocol = 'tcp', $host = null, $port = null, $timeout = 30) { $this->setProtocol($protocol); $this->host = $host; $this->port = $port; $this->timeout = $timeout; // Create the socket. $this->socket = socket_create(AF_INET, SOCK_STREAM, $this->protocol); // Set receive timeout. socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $this->timeout, 'usec' => 0)); // Set send timeout. socket_set_option($this->socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => $this->timeout, 'usec' => 0)); if ($this->socket) { $this->bufferSize = socket_get_option($this->socket, SOL_SOCKET, SO_RCVBUF); // If host and port are specified, connect automatically. if ($this->host && $this->port) { $this->open(); } } else { Logger::get()->error(socket_strerror(socket_last_error())); throw new Exception(socket_strerror(socket_last_error())); } }
$domain = AF_INET6; $level = IPPROTO_IPV6; $s = socket_create($domain, SOCK_DGRAM, SOL_UDP) or die("err"); echo "Setting IPV6_MULTICAST_TTL\n"; $r = socket_set_option($s, $level, IPV6_MULTICAST_HOPS, 9); var_dump($r); $r = socket_get_option($s, $level, IPV6_MULTICAST_HOPS); var_dump($r); echo "\n"; echo "Setting IPV6_MULTICAST_LOOP\n"; $r = socket_set_option($s, $level, IPV6_MULTICAST_LOOP, 0); var_dump($r); $r = socket_get_option($s, $level, IPV6_MULTICAST_LOOP); var_dump($r); $r = socket_set_option($s, $level, IPV6_MULTICAST_LOOP, 1); var_dump($r); $r = socket_get_option($s, $level, IPV6_MULTICAST_LOOP); var_dump($r); echo "\n"; echo "Setting IPV6_MULTICAST_IF\n"; echo "interface 0:\n"; $r = socket_set_option($s, $level, IPV6_MULTICAST_IF, 0); var_dump($r); $r = socket_get_option($s, $level, IPV6_MULTICAST_IF); var_dump($r); echo "interface 1:\n"; $r = socket_set_option($s, $level, IPV6_MULTICAST_IF, 1); var_dump($r); $r = socket_get_option($s, $level, IPV6_MULTICAST_IF); var_dump($r); echo "\n";
/** * Returns the last socket error. Dont call this function twice in a row, it * will loose the error. * * @param socket $socket Socket. Can be null (or non existant). If this is * the case, it will use socket_last_error() to get the error. Otherwise, * it will * try to use socket_get_option() with SO_ERROR. * * @throws Exception if cant get socket error. * @return int The last socket error. */ protected function getSocketErrorNumber($socket = null) { $ret = false; if ($socket === null) { $ret = socket_last_error(); } else { $ret = socket_get_option($socket, SOL_SOCKET, SO_ERROR); if ($ret === false) { throw new Exception('Could not get socket error.'); } } return $ret; }
public function open() { if (\hacklib_cast_as_boolean($this->ipV6_)) { $handle = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } else { $handle = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } if ($handle === false) { $error = "TNonBlockingSocket: Could not create socket"; throw new TTransportException($error); } $this->handle_ = $handle; if (!\hacklib_cast_as_boolean(socket_set_nonblock($this->handle_))) { $error = "TNonBlockingSocket: Could not set nonblocking."; throw new TTransportException($error); } $res = socket_connect($this->handle_, $this->host_, $this->port_); if (!\hacklib_cast_as_boolean($res)) { $errno = socket_last_error($this->handle_); $errstr = socket_strerror($errno); $error = "TNonBlockingSocket: socket_connect error (" . (string) $errstr . "[" . (string) $errno . "])"; if (\hacklib_not_equals($errno, 115)) { if (\hacklib_cast_as_boolean($this->debug_)) { call_user_func($this->debugHandler_, $error); } } throw new TTransportException($error); } $wBuf_ = ""; $rBuf_ = ""; $rBufPos_ = 0; $this->sockRecvCapacity_ = socket_get_option($this->handle_, SOL_SOCKET, SO_RCVBUF); if (\hacklib_equals($this->sockRecvCapacity_, false)) { $this->sockRecvCapacity_ = null; } }
function open() { //Connect timeout Trickkkkkkkkk ##2. NONBLOCKING NEED , less CPU clocking!!^^ //modified by ddaemiri, 2007.08.30 socket_set_nonblock($this->hnd); if (!@socket_connect($this->hnd, $this->ip, $this->port)) { $err = socket_last_error($this->hnd); $err_str = socket_strerror($err); if ($err == 106) { $this->bConnected = true; socket_set_block($this->hnd); return OK; } //EINPROGRESS( Linux:115, Window Socket:10035, FreeBSD4.10:36, ���� OS üũ �Ұ����ؼ� str���ε� �˻� ) if ($err != ERRCODE_INPROGRESS_LINUX && $err != ERRCODE_INPROGRESS_WIN && $err != ERRCODE_INPROGRESS_FREEBSD && $err_str != ERRSTR_INPROGRESS) { $this->error(); socket_close($this->hnd); return SOCK_CONN_ERR; } } $read = array($this->hnd); $write = array($this->hnd); $rtv = @socket_select($read, $write, $except = NULL, TIMEOUT_CONNECT); if ($rtv == 0) { $this->error(); socket_close($this->hnd); return SOCK_TIMEO_ERR; } else { if ($rtv === FALSE) { $this->error(); socket_close($this->hnd); return SOCK_ETC1_ERR; } } if (in_array($this->hnd, $read) || in_array($this->hnd, $write)) { if (@socket_get_option($this->hnd, SOL_SOCKET, SO_ERROR) === FALSE) { $this->error(); socket_close($this->hnd); return SOCK_ETC2_ERR; } } $this->bConnected = true; socket_set_block($this->hnd); return OK; }
/** * Sends a packet via UDP to the list of name servers. * * This function sends a packet to a nameserver. It is called by * send_udp if the sockets PHP extension is compiled into PHP. * * @param string $packet A packet object to send to the NS list * @param string $packet_data The data in the packet as returned by * the Net_DNS_Packet::data() method * @return object Net_DNS_Packet Returns an answer packet object * @see Net_DNS_Resolver::send_tcp(), Net_DNS_Resolver::send(), * Net_DNS_Resolver::send_udp(), Net_DNS_Resolver::send_udp_no_sock_lib() */ function send_udp_with_sock_lib($packet, $packet_data) { $retrans = $this->retrans; $timeout = $retrans; //$w = error_reporting(0); $ctr = 0; // Create a socket handle for each nameserver foreach ($this->nameservers as $nameserver) { if (($sock[$ctr++] = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) && socket_connect($sock[$ctr - 1], $nameserver, $this->port)) { $peerhost[$ctr - 1] = $nameserver; $peerport[$ctr - 1] = $this->port; socket_set_nonblock($sock[$ctr - 1]); } else { $ctr--; } } //error_reporting($w); if ($ctr == 0) { $this->errorstring = 'no nameservers'; return null; } // Try each nameserver up to $this->retry times for ($i = 0; $i < $this->retry; $i++) { if ($i != 0) { // Set the timeout for each retry based on the number of // nameservers there is a connected socket for. $retrans *= 2; $timeout = (int) ($retrans / $ctr); } // Make sure the timeout is at least 1 second if ($timeout < 1) { $timeout = 1; } // Try each nameserver foreach ($sock as $k => $s) { if ($this->debug) { echo "\n;; send_udp(" . $peerhost[$k] . ':' . $peerport[$k] . '): sending ' . strlen($packet_data) . " bytes\n"; } if (!socket_write($s, $packet_data)) { if ($this->debug) { echo ";; send error\n"; } } $set = array($s); if ($this->debug) { echo ";; timeout set to {$timeout} seconds\n"; } $changed = socket_select($set, $w = null, $e = null, $timeout); if ($changed) { // Test to see if the connection was refused. Linux servers will send // an ICMP message which will cause the client's next system call to // return ECONNREFUSED if the server is not listening on the ip:port queried if (socket_get_option($s, SOL_SOCKET, SO_ERROR) == SOCKET_ECONNREFUSED) { // Unix socket connection was refused if ($this->debug) { echo ';; connection to ' . $peerhost[$k] . ':' . $peerport[$k] . " was refused\n"; } // Try the next server. continue; } // Read the response $buf = @socket_read($s, 512); if ($buf === false) { // No data could be read from socket if ($this->debug) { echo ';; no data could be read from ' . $peerhost[$k] . ':' . $peerport[$k] . "\n"; echo ';; socket_error: ' . socket_strerror(socket_last_error()) . "\n"; } // Reset the non-specific socket error status socket_clear_error(); // Try the next server. continue; } $this->answerfrom = $peerhost[$k]; $this->answersize = strlen($buf); if ($this->debug) { echo ';; answer from ' . $peerhost[$k] . ':' . $peerport[$k] . ': ' . strlen($buf) . " bytes\n"; } $ans = new Net_DNS_Packet($this->debug); if ($ans->parse($buf)) { if ($ans->header->qr != '1') { // Ignore packet if it is not a response continue; } elseif ($ans->header->id != $packet->header->id) { // Ignore packet if the response id does not match the query id continue; } else { // Return the DNS response packet $this->errorstring = $ans->header->rcode; $ans->answerfrom = $this->answerfrom; $ans->answersize = $this->answersize; return $ans; } } } elseif ($this->debug) { echo ";; query to " . $peerhost[$k] . ':' . $peerport[$k] . " timed out\n"; } } } $this->errorstring = 'query timed out'; return null; }
function lw_sockCreate($id = 0) { if ($this->Server['Started'] === false) { return false; } $this->err_no(); // DS if (($sci = socket_accept($this->Handler)) === false) { $this->lw_log("socket_accept({$id}) failed: reason: " . socket_strerror(socket_last_error($this->Handler))); return false; } else { if (false === socket_select($Sread = array($sci), $Swrite = null, $Sexcept = null, 0, 1000)) { return false; } } $this->err_yes(); // DS if (isset($this->Connects[$id])) { $this->lw_sockDestroy($id, null, 'Замещён'); } socket_getsockname($sci, $ip); //echo 'SO_KEEPALIVE : '.socket_get_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE).RN; //echo 'SO_REUSEADDR : '.socket_get_option($this->Handler,SOL_SOCKET,SO_REUSEADDR).RN; echo 'SO_RCVBUF : ' . socket_get_option($sci, SOL_SOCKET, SO_RCVBUF) . RN; echo 'SO_SNDBUF : ' . socket_get_option($sci, SOL_SOCKET, SO_SNDBUF) . RN; echo 'SO_DONTROUTE : ' . socket_get_option($sci, SOL_SOCKET, SO_DONTROUTE) . RN; //////// $this->lw_log("Connection created! id: {$id} Addr: {$ip}"); $this->Clients[$id]['Address'] = $ip; $this->Clients[$id]['LastTime'] = $this->Clients[$id]['StartTime'] = microtime(true); $this->Clients[$id]['In'] = $this->Clients[$id]['Out'] = 0; $this->Connects[$id] = $sci; ++$this->Server['Connects']; // wb_create_timer ($_CONTROL['window'], $_SERVER['timer'][$id], CL_SOCKET_TIMER); return true; }
/** * Do a ping of the set hostname * * @return float * Returns a negative number of failure which can be turned into text with * the strError method. A positive number is a response in milliseconds (ms) **/ function Ping() { $this->clearLast(); $type = ""; // icmp echo $code = ""; $checksum = ""; // initial $identifier = $this->getIdentity(); $dec_identity = $this->identity; //$identifier = "\x00\x00"; //$seqNumber = "\x00\x00"; $seqNumber = $this->getSequence(); $dec_sequence = $this->sequence; $data = $this->data_package; $package = $type . $code . $checksum . $identifier . $seqNumber . $data; $checksum = $this->Checksum($package); // proper checksum $package = $type . $code . $checksum . $identifier . $seqNumber . $data; $ip_protocol_code = getprotobyname("ip"); $ip_ttl_code = 7; // Lookup hostname $ips = str_replace(".", "", $this->hostname); if (!is_numeric($ips)) { $host = gethostbyname($this->hostname); if ($host == $this->hostname) { return -5; } } else { $host = $this->hostname; } // Create Socket $socket = socket_create(AF_INET, SOCK_RAW, 1); // @ //or die(socket_strerror(socket_last_error())); if (!$socket) { return -3; } // Set Non-Blocking socket_set_nonblock($socket); // @ $socket_ttl = socket_get_option($socket, $ip_protocol_code, $ip_ttl_code); //for ($a=0; $a<64; $a++) // echo $a." - ".@socket_get_option($socket,$ip_protocol_code,$a)."\n"; if ($this->ttl > 0) { socket_set_option($socket, $ip_protocol_code, $ip_ttl_code, 128); $socket_ttl = socket_get_option($socket, $ip_protocol_code, $ip_ttl_code); //socket_set_option($socket,Socket::IPPROTO_IP,Socket::IP_TTL,128); //$socket_ttl = socket_get_option($socket,Socket::IPPROTO_IP,Socket::IP_TTL); } else { $socket_ttl = 64; } // standard TTL // Connect Socket $sconn = socket_connect($socket, $host, null); // @ if (!$sconn) { return 0; } // Package Size //$package_size = 8+strlen($data); $package_size = strlen($package); // Send Data socket_send($socket, $package, $package_size, 0); // @ // Start Timer $this->startTimer(); $startTime = microtime(true); // need this for the looping section // Read Data $keepon = true; while (false === ($echo_reply = socket_read($socket, 255)) && $keepon) { if (microtime(true) - $startTime > $this->timeout) { $keepon = false; } } if ($keepon) { $elapsed = $this->stopTimer(); socket_close($socket); // @ if ($echo_reply === false) { return -4; } else { if (strlen($echo_reply) < 2) { return -2; } } $rx_parts = unpack("C*", $echo_reply); $tx_parts = unpack("C*", $package); $ipheader = ""; $ipheader_hex = ""; if ($rx_parts[1] == 0x45) { $ipheader = substr($echo_reply, 0, 20); $ipheader_hex = $this->getHex($ipheader); $echo_reply = substr($echo_reply, 20); $rx_parts = unpack("C*", $echo_reply); } if ($this->debug) { echo "\n"; echo " TyCoChksIdenSequData\n"; echo "TX: " . $this->getHex($package) . "\n"; echo "RX: " . $this->getHex($echo_reply) . "\n"; if ($ipheader != "") { echo "HR: " . $ipheader_hex . "\n"; } } $echo_reply_hex = $this->getHex($echo_reply); $reply_type = $rx_parts[1]; $reply_code = $rx_parts[2]; $reply_identity = hexdec(substr($echo_reply_hex, 8, 4)); $reply_sequence = hexdec(substr($echo_reply_hex, 12, 4)); $match = true; if ($ipheader != "") { $source = substr($ipheader_hex, 24, 8); $dest = substr($ipheader_hex, 32, 8); $ttl = hexdec(substr($ipheader_hex, 16, 2)); if ($this->debug) { echo $this->ipAddress($source) . " => " . $this->ipAddress($dest) . " | ttl: " . $ttl . "\n"; } if ($source == $dest) { $match = true; } else { $match = false; } $this->last["set"] = true; $this->last["source"] = $this->ipAddress($source); $this->last["destination"] = $this->ipAddress($dest); $this->last["ttl"] = $ttl; $this->last["hops"] = $socket_ttl - $ttl; } if (($rx_parts[1] == 0 || $rx_parts[1] == 8 && $match) && $rx_parts[2] == 0) { // is echo_reply (0) or is echo_request (8) AND match (from same host) // and has code of 0 // valid response if ($reply_identity != $dec_identity) { return -8; } else { if ($reply_sequence != $dec_sequence) { return -7; } else { $this->last["result"] = $elapsed; return $elapsed; } } } else { // ICMP Error return -9; } } socket_close($socket); // @ return -1; // timeout }
function ask_to_ufdb($datatosend, $PARAMS, $ToUfdbKey) { if (!isset($GLOBALS["UFDB_SOCKET_ERROR"])) { $GLOBALS["UFDB_SOCKET_ERROR"] = 0; } if (!isset($GLOBALS["UfdbgclientMaxSockTimeOut"])) { $GLOBALS["UfdbgclientMaxSockTimeOut"] = 0; } if ($GLOBALS["UfdbgclientMaxSockTimeOut"] == 0) { $GLOBALS["UfdbgclientMaxSockTimeOut"] = 6; } if (intval($GLOBALS["UFDB_SOCKET_ERROR"]) > intval($GLOBALS["UfdbgclientMaxSockTimeOut"])) { if (!isset($GLOBALS["UFDB_SOCKET_ERROR_TIME"])) { $GLOBALS["UFDB_SOCKET_ERROR_TIME"] = time(); return false; } if ($GLOBALS["UFDB_SOCKET_ERROR_TIME"] == 0) { $GLOBALS["UFDB_SOCKET_ERROR_TIME"] = time(); return false; } $ask_to_ufdb_time_sec = ask_to_ufdb_time_sec($GLOBALS["UFDB_SOCKET_ERROR_TIME"]); if ($ask_to_ufdb_time_sec == 10) { ufdbg_admin_mysql(1, "Web filtering Current 10 seconds to wait retry working with webfiltering in 80 seconds...", null, __FILE__, __LINE__); } if ($ask_to_ufdb_time_sec == 30) { ufdbg_admin_mysql(1, "Web filtering Current 30 seconds to wait retry working with webfiltering in 60 seconds...", null, __FILE__, __LINE__); } if ($ask_to_ufdb_time_sec == 60) { ufdbg_admin_mysql(1, "Web filtering Current 60 seconds to wait retry working with webfiltering in 30 seconds...", null, __FILE__, __LINE__); } if ($ask_to_ufdb_time_sec == 80) { ufdbg_admin_mysql(1, "Web filtering Current 80 seconds to wait retry working with webfiltering in 10 seconds...", null, __FILE__, __LINE__); } if ($ask_to_ufdb_time_sec < 89) { return false; } ufdbg_admin_mysql(1, "Web filtering retry working with webfiltering", null, __FILE__, __LINE__); $GLOBALS["UFDB_SOCKET_ERROR"] = 0; $GLOBALS["UFDB_SOCKET_ERROR_TIME"] = 0; } $prefix = "http"; $sitename = $PARAMS["host"]; $uri = $PARAMS["URI"]; $IP = $PARAMS["IP"]; $userid = $PARAMS["userid"]; $PROTO = $PARAMS["PROTO"]; if ($PROTO == "CONNECT") { $prefix = "https"; } if ($userid == "-") { $userid = null; } if (!preg_match("#^http#", $uri)) { $uri = "{$prefix}://{$uri}"; } if (preg_match("#([0-9\\.]+)\\/(.*)#", $IP, $re)) { $hostname = $re[2]; $IP = $re[1]; } $uri = urlencode($uri); if ($GLOBALS["DEBUG_WEBFILTERING"]) { events("ask_to_ufdb: [{$GLOBALS["UFDB_SERVER"]}] Sitename: {$sitename} uri={$uri},IP={$IP},userid={$userid},PROTO={$PROTO}"); } if ($GLOBALS["DEBUG_WEBFILTERING"]) { events("ask_to_ufdb: [{$GLOBALS["UFDB_SERVER"]}] Send \"{$datatosend}\""); } if ($GLOBALS["DEBUG_PROTOCOL"]) { events("[{$GLOBALS["UFDB_SERVER"]}] Send \"{$datatosend}\""); } $socket = @socket_create(AF_INET, SOCK_STREAM, 0); if (!is_resource($socket)) { $GLOBALS["UFDB_SOCKET_ERROR"]++; $error = @socket_strerror(socket_last_error()); events("FATAL!!!: Web filtering socket error {$error} on {$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]} [" . __LINE__ . "]"); ufdbg_admin_mysql(1, "Web filtering socket error {$error} on {$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]} ", null, __FILE__, __LINE__); return false; } $ret = @socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $GLOBALS["UfdbgclientSockTimeOut"], 'usec' => 0)); $ret = socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => $GLOBALS["UfdbgclientSockTimeOut"], 'usec' => 0)); $ret = @socket_get_option($socket, SOL_SOCKET, SO_RCVTIMEO); if ($ret === false) { $error = socket_strerror(socket_last_error()); $GLOBALS["UFDB_SOCKET_ERROR"]++; events("FATAL!!!: Web filtering socket error {$GLOBALS["UFDB_SOCKET_ERROR"]}/{$GLOBALS["UfdbgclientMaxSockTimeOut"]} socket_get_option SO_RCVTIMEO {$error} on {$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]} [" . __LINE__ . "]"); ufdbg_admin_mysql(1, "Web filtering socket error {$GLOBALS["UFDB_SOCKET_ERROR"]}/{$GLOBALS["UfdbgclientMaxSockTimeOut"]} socket_get_option SO_RCVTIMEO {$error} on {$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]} ", null, __FILE__, __LINE__); return false; } if (!@socket_connect($socket, $GLOBALS["UFDB_SERVER"], $GLOBALS["UFDB_PORT"])) { $GLOBALS["UFDB_SOCKET_ERROR"]++; $socket_last_error = socket_last_error($socket); $socketerror = socket_strerror(socket_last_error($socket)); events("ask_to_ufdb: [{$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]}] "); events("FATAL!!!: Web filtering socket error [{$socket_last_error}] {$GLOBALS["UFDB_SOCKET_ERROR"]}/{$GLOBALS["UfdbgclientMaxSockTimeOut"]} {$socketerror} on {$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]} [" . __LINE__ . "]"); ufdbg_admin_mysql(1, "Web filtering socket error [{$socket_last_error}] {$GLOBALS["UFDB_SOCKET_ERROR"]}/{$GLOBALS["UfdbgclientMaxSockTimeOut"]} {$socketerror} on {$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]} ", null, __FILE__, __LINE__); @socket_close($socket); return false; } if ($GLOBALS["DEBUG_PROTOCOL"]) { events("ask_to_ufdb: * * * SEND * * * \"{$datatosend}\"", __LINE__); } @socket_write($socket, $datatosend, strlen($datatosend)); $buf = @socket_read($socket, 1024); if (!$buf) { $socketerror = socket_strerror(socket_last_error($socket)); $GLOBALS["UFDB_SOCKET_ERROR"]++; events("ask_to_ufdb: [{$GLOBALS["UFDB_SERVER"]} Socket error:{$socketerror}"); events("FATAL!!!: Web filtering socket error {$GLOBALS["UFDB_SOCKET_ERROR"]}/{$GLOBALS["UfdbgclientMaxSockTimeOut"]} {$socketerror} on {$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]} [" . __LINE__ . "]"); ufdbg_admin_mysql(1, "Web filtering socket error {$GLOBALS["UFDB_SOCKET_ERROR"]}/{$GLOBALS["UfdbgclientMaxSockTimeOut"]} {$socketerror} on {$GLOBALS["UFDB_SERVER"]}:{$GLOBALS["UFDB_PORT"]} ", null, __FILE__, __LINE__); @socket_close($socket); return false; } @socket_close($socket); $GLOBALS["UFDB_SOCKET_ERROR"] = 0; $buf = str_replace("\r\n", "", $buf); $buf = str_replace("\r", "", $buf); $buf = str_replace("\n", "", $buf); $buf = trim($buf); if ($GLOBALS["DEBUG_PROTOCOL"]) { events("[{$GLOBALS["UFDB_SERVER"]}] RECEIVE \"{$buf}\""); } if ($GLOBALS["DEBUG_WEBFILTERING"]) { events("ask_to_ufdb:[{$GLOBALS["UFDB_SERVER"]}"); } if ($GLOBALS["DEBUG_WEBFILTERING"]) { events("ask_to_ufdb:[{$GLOBALS["UFDB_SERVER"]} **********************"); } if ($GLOBALS["DEBUG_WEBFILTERING"]) { events("ask_to_ufdb:[{$GLOBALS["UFDB_SERVER"]} [proto={$PROTO}]"); } if ($GLOBALS["DEBUG_WEBFILTERING"]) { events("ask_to_ufdb:[{$GLOBALS["UFDB_SERVER"]} Receive \"{$buf}\""); } if ($GLOBALS["DEBUG_WEBFILTERING"]) { events("ask_to_ufdb:[{$GLOBALS["UFDB_SERVER"]} **********************"); } if ($GLOBALS["DEBUG_WEBFILTERING"]) { events("ask_to_ufdb:[{$GLOBALS["UFDB_SERVER"]}"); } if (strpos($buf, "loading-database") > 0) { return $buf; } if (strpos($buf, "fatalerror") > 0) { return $buf; } if ($buf == "OK") { return $buf; } if ($PROTO == "CONNECT") { $url_matched = ask_to_ufdb_parse_response($buf); if ($url_matched != null) { //if(!preg_match("#^https:#", $url_matched)){$url_matched="https://$url_matched";} $url_matched = str_replace("&url=%u", "&url={$uri}", $url_matched); $url_matched = str_replace("&clientaddr=%a", "&clientaddr={$IP}", $url_matched); $url_matched = str_replace("&clientname=%n", "&clientname={$hostname}", $url_matched); $url_matched = str_replace("&clientuser=%i", "&clientuser={$userid}", $url_matched); $url_matched = str_replace("&clientgroup=%s&targetgroup=%t", "&rule-id=0&clientgroup=generic&targetgroup=https-locked", $url_matched); return $url_matched; } } if (strpos(" {$buf}", "GET") > 0) { events_failed("{$buf}"); } if (strpos(" {$buf}", "HTTP/") > 0) { events_failed("{$buf}"); } return $buf; }
/** * Get socket option * * @param int $level * @param int $name * * @throws SocketException * @return mixed */ public function getOption($level, $name) { $value = socket_get_option($this->socket, $level, $name); if (false === $value) { $this->close(); throw new SocketException(); } return $value; }
var_dump($r); $r = socket_get_option($s, $level, IP_MULTICAST_LOOP); var_dump($r); echo "\n"; echo "Setting IP_MULTICAST_LOOP with false\n"; //should convert to (unsigned char)0 $r = socket_set_option($s, $level, IP_MULTICAST_LOOP, false); var_dump($r); $r = socket_get_option($s, $level, IP_MULTICAST_LOOP); var_dump($r); echo "\n"; echo "Setting IP_MULTICAST_TTL with 256\n"; //if we had a simple cast to unsigned char, this would be the same as 0 $r = socket_set_option($s, $level, IP_MULTICAST_TTL, 256); var_dump($r); $r = socket_get_option($s, $level, IP_MULTICAST_TTL); var_dump($r); echo "\n"; echo "Setting IP_MULTICAST_TTL with \"254\"\n"; $r = socket_set_option($s, $level, IP_MULTICAST_TTL, "254"); var_dump($r); $r = socket_get_option($s, $level, IP_MULTICAST_TTL); var_dump($r); echo "\n"; echo "Setting IP_MULTICAST_TTL with -1\n"; //should give error, not be the same as 255 $r = socket_set_option($s, $level, IP_MULTICAST_TTL, -1); var_dump($r); $r = socket_get_option($s, $level, IP_MULTICAST_TTL); var_dump($r); echo "\n";
public function get_option($level, $optname) { $optval = @socket_get_option($this->socketResource, $level, $optname); if ($optval === false) { throw new Socket_Exception("Failed to get socket option", socket_last_error()); } return $optval; }
static function getRegSpamScore(&$score, array $user, $verbose, $debug, $model) { $o = XenForo_Application::getOptions(); if (trim($o->TPUDetectSpamRegOpenPort) != '') { if (!function_exists('socket_create')) { $model->logScore('PHP function socket_create() not available, you need the PHP socket extension for open port detection to work', 0); return; } $entries = array(); $socks = array(); foreach (explode("\n", $o->TPUDetectSpamRegOpenPort) as $entry) { $entry = explode('|', trim($entry)); if (count($entry) != 2) { continue; } list($points, $port) = $entry; if (!is_numeric($port)) { $port = getservbyname($port, 'tcp'); } if ($port > 0) { socket_clear_error(); if (self::isIPv6($user['ip'])) { $sock = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } else { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } socket_set_nonblock($sock); @socket_connect($sock, $user['ip'], $port); $errno = socket_last_error(); if ($errno == SOCKET_EALREADY || $errno == SOCKET_EINPROGRESS || $errno == 0) { $socks[] = $sock; } else { socket_close($sock); } $entries[] = array('points' => $points, 'port' => $port, 'open' => false); } } $start = microtime(true); while ($socks && microtime(true) - $start < self::TIMEOUT) { $null = null; $write = $socks; socket_select($null, $write, $null, 1); foreach ($write as $k => $sock) { $errno = socket_get_option($sock, SOL_SOCKET, SO_ERROR); if ($errno == 0) { $entries[$k]['open'] = true; } elseif ($errno == SOCKET_ECONNREFUSED) { } elseif ($errno == SOCKET_ETIMEDOUT) { } else { $errmsg = socket_strerror($errno); } unset($socks[$k]); socket_close($sock); } } foreach ($entries as $entry) { if ($entry['open']) { $model->logScore('tpu_detectspamreg_port_fail', $entry['points'], array('port' => $entry['port'])); $points = $entry['points']; if (is_numeric($points)) { $score['points'] += $points; } else { $score[$points] = true; } } else { if ($debug) { $model->logScore('tpu_detectspamreg_port_ok', 0, array('port' => $entry['port'])); } } } } }
/** * Create socket connection * * @return null|resource */ protected function _createSocketConnection() { $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1); @socket_set_nonblock($socket); $result = @socket_connect($socket, $this->getHost(), $this->getPort()); if ($result === false) { $errorCode = socket_last_error($socket); if ($errorCode !== SOCKET_EINPROGRESS) { return null; } } else { //@socket_set_block($socket); return $socket; } /* Do whatever we want while the connect is taking place. */ $result = @socket_select($r = array($socket), $w = array($socket), $e = array($socket), $this->getTimeout()); if ($result === 0 || $result === false) { return null; } if (!($r && count($r) || $w && count($w)) || @socket_get_option($socket, SOL_SOCKET, SO_ERROR) != 0) { return null; } //@socket_set_block($socket); return $socket; }
/** * @param $level * @param $optname * * @return mixed * @throws Exception\Exception_Socket */ public function getOption($level, $optname) { $return = @socket_get_option($this->resource, $level, $optname); if ($return === false) { throw new Exception_Socket($this->resource); } return $return; }
public function GetOption($optname) { if (socket_get_option($this->Handle, SOL_SOCKET, $optname) === false) { throw new SocketException('Could not retreive socket option: ' . $this->StringError()); } }
/** * Gets socket options. * * <p>Retrieves the value for the option specified by the optname parameter for the current socket.</p> * * @param int $level <p>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 <code>SOL_SOCKET</code> would be used. Other * levels, such as <code>TCP</code>, can be used by specifying the protocol number of that level. Protocol numbers * can be found by using the <code>getprotobyname()</code> function. * @param int $optname <p><b>Available Socket Options</b></p><p><code>SO_DEBUG</code> - Reports whether debugging * information is being recorded. Returns int.</p><p><code>SO_BROADCAST</code> - Reports whether transmission of * broadcast messages is supported. Returns int.</p><p><code>SO_REUSERADDR</code> - Reports whether local addresses * can be reused. Returns int.</p><p><code>SO_KEEPALIVE</code> - Reports whether connections are kept active with * periodic transmission of messages. If the connected socket fails to respond to these messages, the connection is * broken and processes writing to that socket are notified with a SIGPIPE signal. Returns int.</p><p> * <code>SO_LINGER</code> - Reports whether the socket lingers on <code>close()</code> if data is present. By * default, when the socket is closed, it attempts to send all unsent data. In the case of a connection-oriented * socket, <code>close()</code> will wait for its peer to acknowledge the data. If <code>l_onoff</code> is non-zero * and <code>l_linger</code> is zero, all the unsent data will be discarded and RST (reset) is sent to the peer in * the case of a connection-oriented socket. On the other hand, if <code>l_onoff</code> is non-zero and * <code>l_linger</code> is non-zero, <code>close()</code> will block until all the data is sent or the time * specified in <code>l_linger</code> elapses. If the socket is non-blocking, <code>close()</code> will fail and * return an error. Returns an array with two keps: <code>l_onoff</code> and <code>l_linger</code>.</p><p> * <code>SO_OOBINLINE</code> - Reports whether the socket leaves out-of-band data inline. Returns int.</p><p> * <code>SO_SNDBUF</code> - Reports the size of the send buffer. Returns int.</p><p><code>SO_RCVBUF</code> - * Reports the size of the receive buffer. Returns int.</p><p><code>SO_ERROR</code> - Reports information about * error status and clears it. Returns int.</p><p><code>SO_TYPE</code> - Reports the socket type (e.g. * <code>SOCK_STREAM</code>). Returns int.</p><p><code>SO_DONTROUTE</code> - Reports whether outgoing messages * bypass the standard routing facilities. Returns int.</p><p><code>SO_RCVLOWAT</code> - Reports the minimum number * of bytes to process for socket input operations. Returns int.</p><p><code>SO_RCVTIMEO</code> - Reports the * timeout value for input operations. Returns an array with two keys: <code>sec</code> which is the seconds part * on the timeout value and <code>usec</code> which is the microsecond part of the timeout value.</p><p> * <code>SO_SNDTIMEO</code> - Reports the timeout value specifying the amount of time that an output function * blocks because flow control prevents data from being sent. Returns an array with two keys: <code>sec</code> * which is the seconds part on the timeout value and <code>usec</code> which is the microsecond part of the * timeout value.</p><p><code>SO_SNDLOWAT</code> - Reports the minimum number of bytes to process for socket output * operations. Returns int.</p><p><code>TCP_NODELAY</code> - Reports whether the Nagle TCP algorithm is disabled. * Returns int.</p><p><code>IP_MULTICAST_IF</code> - The outgoing interface for IPv4 multicast packets. Returns the * index of the interface (int).</p><p><code>IPV6_MULTICAST_IF</code> - The outgoing interface for IPv6 multicast * packets. Returns the same thing as <code>IP_MULTICAST_IF</code>.</p><p><code>IP_MULTICAST_LOOP</code> - The * multicast loopback policy for IPv4 packets, which determines whether multicast packets sent by this socket also * reach receivers in the same host that have joined the same multicast group on the outgoing interface used by * this socket. This is the case by default. Returns int.</p><p><code>IPV6_MULTICAST_LOOP</code> - Analogous to * <code>IP_MULTICAST_LOOP</code>, but for IPv6. Returns int.</p><p><code>IP_MULTICAST_TTL</code> - The * time-to-live of outgoing IPv4 multicast packets. This should be a value between 0 (don't leave the interface) * and 255. The default value is 1 (only the local network is reached). Returns int.</p><p> * <code>IPV6_MULTICAST_HOPS</code> - Analogous to <code>IP_MULTICAST_TTL</code>, but for IPv6 packets. The value * -1 is also accepted, meaning the route default should be used. Returns int.</p> * * @throws Exception\SocketException If there was an error retrieving the option. * * @return mixed See the descriptions based on the option being requested above. */ public function getOption($level, $optname) { return static::exceptionOnFalse($this->resource, function ($resource) use($level, $optname) { return @socket_get_option($resource, $level, $optname); }); }
/** * get socket option * * @param int $level * @param int $optname * @return mixed * @throws Exception on error * @uses socket_get_option() */ public function getOption($level, $optname) { $value = @socket_get_option($this->resource, $level, $optname); if ($value === false) { throw Exception::createFromSocketResource($this->resource); } return $value; }
*/ //Reduce errors error_reporting(~E_WARNING); //Create a UDP socket if (!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [{$errorcode}] {$errormsg} \n"); } if (!socket_set_option($sock, SOL_SOCKET, SO_KEEPALIVE, 1)) { echo "socket_set_option SO_KEEPALIVE failed\n"; } else { $option = socket_get_option($sock, SOL_SOCKET, SO_KEEPALIVE); echo "SO_KEEPALIVE = " . $option . "\n"; } if (($options = socket_get_option($sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 10, 'usec' => 0))) === FALSE) { echo "socket_set_option for SO_RCVTIMEO failed\n"; } else { echo "SO_RCVTIMEO = 5 seconds\n"; } $localURL = "esp8266.local"; $count = 0; $remote_port = '2652'; $secCnt = 0; $outputArray = array(); $execRet; //Do some communication, this loop can handle multiple clients if (isset($argv[1])) { if (is_ipv4($argv[1])) { $remote_ip = $argv[1]; } else {
define("MAX_DATA_LEN", 10000); error_reporting(E_ALL); set_time_limit(0); ob_implicit_flush(); date_default_timezone_set("UTC"); if (file_exists(BUFFER_FILE) == False) { echo "*** named pipe file not found\n"; return; } $buffer = fopen(BUFFER_FILE, "r"); $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($server === False) { echo "*** socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; return; } if (socket_get_option($server, SOL_SOCKET, SO_REUSEADDR) === False) { echo "*** socket_get_option() failed: reason: " . socket_strerror(socket_last_error($server)) . "\n"; return; } if (@socket_bind($server, LISTEN_ADDRESS, LISTEN_PORT) === False) { echo "*** socket_bind() failed: reason: " . socket_strerror(socket_last_error($server)) . "\n"; return; } if (socket_listen($server, 5) === False) { echo "*** socket_listen() failed: reason: " . socket_strerror(socket_last_error($server)) . "\n"; return; } $clients = array($server); echo "exec output server\n"; echo "listening on " . LISTEN_ADDRESS . "...\n"; while (True) {
/** * Write (all) data to the socket. * Timeout throws SocketTransportException * * @param integer $length */ public function write($buffer, $length) { $r = $length; $writeTimeout = socket_get_option($this->socket, SOL_SOCKET, SO_SNDTIMEO); while ($r > 0) { $wrote = socket_write($this->socket, $buffer, $r); if ($wrote === false) { throw new SocketTransportException('Could not write ' . $length . ' bytes to socket; ' . socket_strerror(socket_last_error()), socket_last_error()); } $r -= $wrote; if ($r == 0) { return; } $buffer = substr($buffer, $wrote); // wait for the socket to accept more data, up to timeout $r = null; $w = array($this->socket); $e = array($this->socket); $res = socket_select($r, $w, $e, $writeTimeout['sec'], $writeTimeout['usec']); // check if ($res === false) { throw new SocketTransportException('Could not examine socket; ' . socket_strerror(socket_last_error()), socket_last_error()); } if (!empty($e)) { throw new SocketTransportException('Socket exception while waiting to write data; ' . socket_strerror(socket_last_error()), socket_last_error()); } if (empty($w)) { throw new SocketTransportException('Timed out waiting to write data on socket'); } } }
public function getWriteTimeout() { $timeVal = socket_get_option($this->socket, SOL_SOCKET, SO_RCVTIMEO); return $timeVal['sec'] * 1000 + (int) ($timeVal['usec'] / 1000); }
<?php $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!$socket) { die('Unable to create AF_INET socket [socket]'); } // wrong params $retval_1 = socket_set_option($socket, SOL_SOCKET, SO_LINGER, array()); // set/get comparison $options = array("l_onoff" => 1, "l_linger" => 1); $retval_2 = socket_set_option($socket, SOL_SOCKET, SO_LINGER, $options); $retval_3 = socket_get_option($socket, SOL_SOCKET, SO_LINGER); //l_linger not given $options_2 = array("l_onoff" => 1); var_dump(socket_set_option($socket, SOL_SOCKET, SO_LINGER, $options_2)); var_dump($retval_2); var_dump($retval_3["l_linger"] === $options["l_linger"]); // value of l_onoff is not always 1, Darwin returns 128 var_dump((bool) $retval_3["l_onoff"] === (bool) $options["l_onoff"]); socket_close($socket); ?>