Does anyone know how to set the timeout of fsockopen? I set 5 in the #fsockopen line but it seems much shorter when it fails?
$socket = #fsockopen(Config::get('client.host'), Config::get('client.port'), $errno, $errstr, 5);
if (!$socket) {
return false;
}
else {
fclose($socket);
return true;
}
The timeout parameter sets the maximum time a function should block.
If an error occurs, the function can return way before it hit the timeout.
Examine the $errno/$errstr variables to diagnose the problem.
Related
I am currently developing a Online Controlled home but I have a problem with the internet connection checker.
I have this code to detect whether there is an internet connection or there is no internet connection.
$check = #fsockopen("www.google.com", 80);
if($check){
return true;
fclose($check);
}else{
return false;
fclose($check);
}
but the problem is, when my Raspberry Pi don't have an internet connection then it continuously load the page forever.
the full script is here
<?php
function checkConnection(){
$check = #fsockopen("www.google.com", 80);
if($check){
return true;
fclose($check);
}else{
return false;
fclose($check);
}
}
if(checkConnection()==true){
echo '[{"status":"success","result":"Internet Connection is Available"}]';
}else{
echo '[{"status":"fail","result":"No Internet Connection"}]';
}
?>
fsockopen takes a timeout as the last param, which only applies while connection the socket
DNS lookup can be a factor too, AFAIK you can't control the timeout for that, unless if you're going to use gethostbyname() in that case you can use
putenv('RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1');
to limit DNS lookup to 1s.
Based on your code here's how i would implement it.
function is_connected()
{
//1. provide a timeout to your socket
//2. use example.com as a domain, that's what it's made for (testing)
$socket = #fsockopen("www.example.com", 80, $err_no, $err_str, 5);
if ($socket){
fclose($socket);
return true;
}
return false;
}
$success = json_encode(["status" => "success","result" => "Internet is Available"]);
$failure = json_encode(["status" => "fail","result" => "Internet is Unavailable"]);
echo is_connected() ? $success : $failure;
Perhaps a small change in your function might enlighten the situation. For example:
function checkConnection() {
$fp = #fsockopen("www.google.com", 80, $errno, $errstr, 3);
if (!$fp) {
return "$errstr ($errno)<br />\n";
} else {
return true;
}
}
$con = checkConnection();
if ($con===true) {
echo json_encode( ["status" => "success","result" => "Internet Connection is Available"] );
} else {
// should not be - No Internet Connection is Available
echo json_encode( ["status" => "fail","result" => $con] );
}
PS: Try it out in PHPFiddle and make sure to change the port from 80 to 83 for example. This of course does not mean that you don't have internet connection but that the host you reach at the specified port does not reply. Anyway it will simply fail the function and return the error message. Also please do notice the timeout limit of 3 seconds in fsocopen since you may alter it accordingly to your needs.
EDIT
A simpler and perhaps more accurate approach on what you are trying to do could be this.
function checkConnection($hostname) {
$fp = gethostbyname($hostname);
if (!inet_pton($fp)) {
return json_encode( ["status" => "fail","result" => "Internet Connection is not Available or Host {$hostname} is wrong or does not exist."] );
} else {
return json_encode( ["status" => "success","result" => "Internet Connection is Available. Host {$hostname} exists and resolves to {$fp}"] );
}
}
echo checkConnection('www.google.com');
You might want to check this comment in php.net on setting alternative options for gethostbyname.
I am trying to make a server status page for my game server and the code ends up not showing if the server is online.
<?PHP
$ts_ip = "177.82.148.141";
$ts_port = "2505";
$output = #fsockopen("$ts_ip", $ts_port, $errno, $errstr, 2);
stream_set_timeout($output, 00002);
if (!$output) {
echo "<FONT COLOR=#DD0000><B>FEB Offline</B></FONT>";
} else {
echo "<FONT COLOR=#00DD00><B>FEB Online</B></FONT>";
}
#fclose($output);
?>
It also gives me this error:
Warning: stream_set_timeout() expects parameter 1 to be resource, boolean given in /home/u918484727/public_html/teste.php on line 6
May someone help me?
"$ts_ip" shouldn't have " round them?
There's probably a better way to handle this but this will make it work.
$ts_ip = "177.82.148.141";
$ts_port = "2505";
$output = #fsockopen($ts_ip, $ts_port, $errno, $errstr, 2);
if (!$output) {
echo "<FONT COLOR=#DD0000><B>FEB Offline</B></FONT>";
} else {
echo "<FONT COLOR=#00DD00><B>FEB Online</B></FONT>";
stream_set_timeout($output, 00002);
#fclose($output);
}
I put $output logic in the else so that your code doesn't attempt to use it as a resource when it returns false.
Also, although it isn't the cause of the problem, as supajason pointed out you should probably use $ts_ip instead of "$ts_ip". You should also refactor your code in other ways, such as removing the # error suppression.
Oh boy have I got myself a predicament here.
Let's start by sharing some of my code.
ini_set('max_execution_time', 0);
ini_set('default_socket_timeout', 0);
set_time_limit(0);
ignore_user_abort(true);
$data = '';
$server = pfsockopen("//", 9001, $errno, $errdesc, 99999);
socket_set_timeout($server, 0);
while(!feof($server))
{
$data .= fgets($server, 2048);
parse_str($data);
if(!$data == '')
{
if($prot == "message")
{
message($destination, $body, $time);
}
else
{
return "cocks";
}
}
sleep(1);
}
Alright so basically. I want this script to run inifnitely because it listens to a chat server. It takes chat server input the and an optional amount of time it wants to send the message to be available for. My function looks somewhat like this:
function message($destination, $body, $time)
{
do
{
socket connection
if(! socket isn't available)
{
return "$errno ($errdesc)";
}
else
{
while(true)
{
while true write some stuff.
}
}
} while(true);
}
The part I'm struggling with is the function because it just doesn't want to stop after. Any help would be greatly appreciated.
I DO NOT WANT JAVASCRIPT/ETC ALTERNATIVES. THIS MUST BE DONE IN PHP.
Still looking for some help here.
I am wanting to send a packet to a server using PHP. I am trying to figure out how to conect with a predetermined IP, port and socket id. However, my code does not seem to be working properly, although no error is being shown.
function SendData($data){
$ip = "1.1.1.1";
$port = 31000;
$my_sock = '525'
$sock = fsockopen($ip, $port, $errnum, $errstr, $timeout);
if(!is_resource($sock)){
return false;
} else {
fputs($sock, $data);
return true;
}
SendData("#E");
SendData("DJ");
fclose($sock);
}
I am also considering doing this in Javascript, if possible. Whichever way works best.
Doesn't your SendData function go into infinite recursion? Something like:
SendData('X')
fsockopen(...)
SendData('#E')
fsockopen(...)
SendData('#E')
fsockopen(...)
SendData('#E')
...
I need to check if a group of servers, routers and switches is alive. I have been searching for something reliable that would work with IPs and ports for over an hour now, could anyone help?
Ended up using
function ping($addr, $port='') {
if(empty($port)) {
ob_start();
system('ping -c1 -w1 '.$addr, $return);
ob_end_clean();
if($return == 0) {
return true;
} else {
return false;
}
} else {
$fp = fsockopen("udp://{$addr}", $port, $errno, $errstr);
if (!$fp) {
return false;
} else {
return true;
}
}
}
Servers, routers and switches...the one commonality that all of them share is the ability to accept SNMP requests if an SNMP service is running. Sounds like what you are trying to do is implement a funny workaround to a monitoring system (nagios, etc....)
As per: http://php.net/manual/en/book.snmp.php
<?php
$endpoints = array('10.0.0.1','10.0.0.2','10.0.0.3','10.0.0.4','10.0.0.5');
foreach ($endpoints as $endpoint) {
$session = new SNMP(SNMP::VERSION_2c, $endpoint, 'boguscommunity');
var_dump($session->getError());
// do something with the $session->getError() if it exists else, endpoint is up
}
?>
This will tell you if the endpoint is alive and the SNMP service is running. Specific to seeing if the port is available / open, you can use fsockopen():
http://php.net/manual/en/function.fsockopen.php
<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br />\n";
}
?>
$ip = "123.456.789.0";
$ping = exec("ping -c 1 -s 64 -t 64 ".$ip);
var_dump($ping);
// and so forth.
if you are checking for mysql you can use something like
if (mysqli_ping($ip)) echo "sweet!";
else echo "oh dam";
I would be a little concerned using the ping option as that can be blocked, and out of no where ...