Нужен простой код проверки сервера на отклик

Sam_Fisher

Участник
Сообщения
703
Реакции
203
Здравствуйте дорогие форумчане и веб знатоки. Озадачился таким вопросом. Хотелось бы на сайте разместить сообщение о техническом статусе сервера: включен или выключен. (уж очень устал вручную редачить код всякий раз)
Выглядеть это будет так:

Технический статус сервера: Отключен
Технический статус сервера: Работает

Я в этом не силен, потому и прошу помочь. Код может быть как php так и html
 

Webman

Nevermind
Сообщения
803
Реакции
330
PHP:
<?php
 
$ip = ""; // IP сервера
$port = ""; // Порт сервера
 
function GetServerInfo($ip,$port) {
   $fp = @fsockopen("udp://".$ip, $port);
   if (!$fp) return false;
 
    @fwrite($fp,"\xFF\xFF\xFF\xFF\x54\x53\x6F\x75\x72\x63\x65\x20\x45\x6E\x67\x69\x6E\x65\x20\x51\x75\x65\x72\x79\x00".chr(10));
    $start=time();
    socket_set_timeout($fp,1);
    $st=fread($fp,1);
    $r=socket_get_status($fp);
    $result['status'] = $r["timed_out"];
    $r=$r["unread_bytes"];
    if ($r == 0) { @fclose($fp); return false;}
    $st.=fread($fp,$r);
    @fclose($fp);
   
    return $result;
}
    $info = GetServerInfo($ip, $port);
        if (!$info) print "Технический статус сервера: <span style=\"color: red;\">Отключен</span>";
        else print "Технический статус сервера: <span style=\"color: green;\">Работает</span>";

?>

Вписываешь IP, PORT в кавычки.
 

Sam_Fisher

Участник
Сообщения
703
Реакции
203
Webman, у меня выписывает:
PHP:
Parse error: syntax error, unexpected 'color' (T_STRING) in /home/u799271676/public_html/admin/applications_addon/other/portal/modules_public/portal/portal.php(149) : eval()'d code on line 24
P.S. Использую код на IPB

А вот сам файл портала:
PHP:
<?php
/*
+--------------------------------------------------------------------------
|   Portal 1.4.0
|   =============================================
|   by Michael John
|   Copyright 2011-2013 DevFuse
|   http://www.devfuse.com
+--------------------------------------------------------------------------
|   Based on IP.Board Portal by Invision Power Services
|   Website - http://www.invisionpower.com/
+--------------------------------------------------------------------------
*/

if ( ! defined( 'IN_IPB' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
	exit();
}

class public_portal_portal_portal extends ipsCommand
{
	/**
	 * Array of portal objects
	 *
	 * @access	protected
	 * @var 	array 				Registered portal objects
	 */
	protected $portal_object		= array();

	/**
	 * Array of replacement tags
	 *
	 * @access	protected
	 * @var 	array 				Replacement tags
	 */
	protected $replace_tags			= array();
	
	/**
	 * Array of tags to module...
	 *
	 * @access	protected
	 * @var 	array 				Tags => Modules mapping
	 */
	protected $remap_tags_module 	= array();
	
	/**
	 * Array of tags to function...
	 *
	 * @access	protected
	 * @var 	array 				Tags => Function mapping
	 */
	protected $remap_tags_function	= array();
	
	/**
	 * Array of module objects
	 *
	 * @access	protected
	 * @var 	array 				Module objects
	 */
	protected $module_objects		= array();
	
	/**
	 * Basic template, replaced as needed
	 *
	 * @access	protected
	 * @var 	string 				Basic skin template to replace
	 */
	protected $template				= array();

	/**
	 * Main class entry point
	 *
	 * @access	public
	 * @param	object		ipsRegistry reference
	 * @return	void		[Outputs to screen]
	 */
	public function doExecute( ipsRegistry $registry ) 
	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		$conf_groups		= array();
		$found_tags			= array();
		$found_modules		= array();
		
		//-----------------------------------------
		// Make sure the portal is installed an enabled
		//-----------------------------------------
		
		if( ! IPSLib::appIsInstalled( 'portal' ) )
		{
			$this->registry->output->showError( 'no_permission', 1076, null, null, 404 );
		}
		
		//-----------------------------------------
		// Get settings...
		//-----------------------------------------
		
		foreach( $this->cache->getCache('portal') as $portal_data )
		{
			if( ! IPSLib::appIsInstalled( $portal_data['_app_dir'] ) )
			{
				continue;
			}
			
			//-----------------------------------------
			// Remap tags
			//-----------------------------------------
			
			if ( is_array( $portal_data['pc_exportable_tags'] ) AND count( $portal_data['pc_exportable_tags'] ) )
			{
				foreach( $portal_data['pc_exportable_tags'] as $tag => $tag_data )
				{
					$this->remap_tags_function[ $tag ]	= $tag_data[0];
					$this->remap_tags_module[ $tag ]	= $portal_data['pc_key'];
				}
			}
		}		

		//-----------------------------------------
		// Get global skin and language files
		//-----------------------------------------
		
		ipsRegistry::getClass( 'class_localization')->loadLanguageFile( array( 'public_portal' ) );

		//-----------------------------------------
		// Assign skeletal template ma-doo-bob
		//-----------------------------------------
        
		$this->DB->build( array( 'select' => '*', 'from' => 'portal_blocks', 'order' => 'position ASC', 'where' => "show_block=1" ) );
		$this->DB->execute();
		
		$leftBlocks  = array();	
		$mainBlocks  = array();        
		$rightBlocks = array();
        		 
		while( $r = $this->DB->fetch() )
		{          
            $portalBlocks[] = $r;            					 	
		}    
        
        if( is_array( $portalBlocks ) AND count( $portalBlocks ) )
        {
            foreach( $portalBlocks as $block )
            {
                ob_start();
                eval("?>".$block['block_code']."<?php\n");
                $block['block_code'] = ob_get_contents();
                ob_end_clean();	
                
                if( $block['align'] == '1' )
                {
                    $leftBlocks[] = $block;    
                }
                else if( $block['align'] == '2' )
                {
                    $mainBlocks[] = $block;    
                }
                else if( $block['align'] == '3' )
                {
                    $rightBlocks[] = $block;    
                } 
                else if( $block['align'] == '4' )
                {
                    $topBlocks[] = $block;    
                } 
                else if( $block['align'] == '5' )
                {
                    $bottomBlocks[] = $block;    
                }                                          
            }            
        }
        		
		$this->template = $this->registry->getClass('output')->getTemplate('portal')->skeletonTemplate( $leftBlocks, $mainBlocks, $rightBlocks, $topBlocks, $bottomBlocks );
        
		
		//-----------------------------------------
		// Grab all special tags
		//-----------------------------------------
		
		preg_match_all( "#<!--\:\:(.+?)\:\:-->#", $this->template, $match );
		
		//-----------------------------------------
		// Assign functions
		//-----------------------------------------
		
		for ( $i=0, $m=count($match[0]); $i < $m; $i++ )
		{
			$tag = $match[1][$i];
			
			if ( $this->remap_tags_module[ $tag ] )
			{
				$found_tags[ $tag ] = 1;
				
				if ( $this->remap_tags_module[ $tag ])
				{
					$found_modules[ $this->remap_tags_module[ $tag ] ] = 1;
				}
			}
		}
			
		//-----------------------------------------
		// Require modules...
		//-----------------------------------------
		
		if ( is_array( $found_modules ) AND count( $found_modules ) )
		{
			foreach( $found_modules as $mod_name => $pointless )
			{
				if ( ! is_object( $this->module_objects[ $mod_name ] ) )
				{
					if ( file_exists( $this->caches['portal'][ $mod_name ]['_file_location'] ) )
					{
						$constructor = IPSLib::loadLibrary( $this->caches['portal'][ $mod_name ]['_file_location'], 'ppi_' . $mod_name, $this->caches['portal'][ $mod_name ]['_app_dir'] );
						$this->module_objects[ $mod_name ] = new $constructor();
						$this->module_objects[ $mod_name ]->makeRegistryShortcuts( $this->registry );
                        
                        if( method_exists($this->module_objects[ $mod_name ], 'init') )
                        {
                            $this->module_objects[ $mod_name ]->init();    
                        }
					}
				}
			}
		}
		
		//-----------------------------------------
		// Get the tag replacements...
		//-----------------------------------------
		
		if ( is_array( $found_tags ) AND count( $found_tags ) )
		{
			foreach( $found_tags as $tag_name => $even_more_pointless )
			{
				$mod_obj	= $this->remap_tags_module[ $tag_name ];
				$fun_obj	= $this->remap_tags_function[ $tag_name ];
				
				if ( method_exists( $this->module_objects[ $mod_obj ], $fun_obj ) )
				{
					$this->replace_tags[ $tag_name ] = $this->module_objects[ $mod_obj ]->$fun_obj();
					continue;
				}
			}
		}
		
		$this->_do_output();
 	}
 	
 	/**
 	 * Internal do output method.  Extend class and overwrite method if you need to modify this functionality.
 	 *
 	 * @access	protected
 	 * @return	void
 	 */
 	protected function _do_output()
 	{
 		//-----------------------------------------
		// SITE REPLACEMENTS
		//-----------------------------------------
		
		foreach( $this->replace_tags as $sbk => $sbv )
		{
			$this->template = str_replace( "<!--::" . $sbk . "::-->", $sbv, $this->template );
		}
        
   	    //-----------------------------------------
        // Meta tags
        //-----------------------------------------
    
        if( $this->settings['portal_index_md'] )
        {
            $this->registry->output->addMetaTag( 'description', $this->settings['portal_index_md'], false );
        }
        
        if( $this->settings['portal_index_mk'] )
        {
            $this->registry->output->addMetaTag( 'keywords', $this->settings['portal_index_mk'], false );
        }        
 		
 		//-----------------------------------------
 		// Pass to print...
 		//-----------------------------------------
        
        $portalTitle = ( $this->settings['portal_index_title'] ) ? $this->settings['portal_index_title'] : $this->lang->words['portal_title'] .' - '. $this->settings['board_name'];
 		
 		$this->registry->output->addContent( $this->template );
 		$this->registry->output->setTitle( $portalTitle );
 		$this->registry->output->addNavigation( $this->lang->words['portal_title'], 'app=portal', "false", 'app=portal' );
        
		# Removal of this copyright code without purchasing copyright removal is illegal and violates your license agreement.       
        if( !$this->settings['devfuse_copy_num_free'] )
        {
            $this->registry->output->addContent( "<br /><div class='ipsType_smaller desc lighter right' style='clear: both; text-align:right;'></div>" );    
        }
 		
 		$this->registry->output->sendOutput();

		exit();
 	}

}
 

Webman

Nevermind
Сообщения
803
Реакции
330
Для чего файл портала скинул? Я не понял.
Куда ты скинутый выше мною код вставлял?
 

Sam_Fisher

Участник
Сообщения
703
Реакции
203

★Сириус★

Участник
Сообщения
743
Реакции
197
PHP:
<?php
 
$ip = ""; // IP сервера
$port = ""; // Порт сервера
 
function GetServerInfo($ip,$port) {
   $fp = @fsockopen("udp://".$ip, $port);
   if (!$fp) return false;
 
    @fwrite($fp,"\xFF\xFF\xFF\xFF\x54\x53\x6F\x75\x72\x63\x65\x20\x45\x6E\x67\x69\x6E\x65\x20\x51\x75\x65\x72\x79\x00".chr(10));
    $start=time();
    socket_set_timeout($fp,1);
    $st=fread($fp,1);
    $r=socket_get_status($fp);
    $result['status'] = $r["timed_out"];
    $r=$r["unread_bytes"];
    if ($r == 0) { @fclose($fp); return false;}
    $st.=fread($fp,$r);
    @fclose($fp);
   
    return $result;
}
    $info = GetServerInfo($ip, $port);
        if (!$info) print "Технический статус сервера: <span style=\"color: red;\">Отключен</span>";
        else print "Технический статус сервера: <span style=\"color: green;\">Работает</span>";

?>

Вписываешь IP, PORT в кавычки.

спасибо работает отлично
 

HooLIGUN

MatchMaking CS:S / RGMIX.ru
Сообщения
1,069
Реакции
269
я вставил код в блок. Оффтоп - сайт. не реклама!!!
а файл портала приложил, потому что ругается и ссылается на этот файл
Как вариант для ipb:
создать php файл с кодом,залить на сервер сайта , вывести фреймом в нужное место
C-подобный:
<iframe frameborder="0" src="/server.php" <p><br />Your browser does not support iframes.</p> </iframe>
 

Webman

Nevermind
Сообщения
803
Реакции
330
Попробуй так:
PHP:
 <?php
 
$ip = ""; // IP сервера
$port = ""; // Порт сервера
 
function GetServerInfo($ip,$port) {
   $fp = @fsockopen("udp://".$ip, $port);
   if (!$fp) return false;
 
    @fwrite($fp,"\xFF\xFF\xFF\xFF\x54\x53\x6F\x75\x72\x63\x65\x20\x45\x6E\x67\x69\x6E\x65\x20\x51\x75\x65\x72\x79\x00".chr(10));
    $start=time();
    socket_set_timeout($fp,1);
    $st=fread($fp,1);
    $r=socket_get_status($fp);
    $result['status'] = $r["timed_out"];
    $r=$r["unread_bytes"];
    if ($r == 0) { @fclose($fp); return false;}
    $st.=fread($fp,$r);
    @fclose($fp);
   
    return $result;
}
    $info = GetServerInfo($ip, $port);
        if (!$info) print "Технический статус сервера: <span style='color:red;'>Отключен</span>";
        else print "Технический статус сервера: <span style='color:green;'>Работает</span>";

?>
Добавлено через 6 минут
HooLIGUN, Будет работать, но это не выход, засорять сайт фреймами не стоит.
 
Последнее редактирование:

Sam_Fisher

Участник
Сообщения
703
Реакции
203
Попробуй так:
PHP:
 <?php
 
$ip = ""; // IP сервера
$port = ""; // Порт сервера
 
function GetServerInfo($ip,$port) {
   $fp = @fsockopen("udp://".$ip, $port);
   if (!$fp) return false;
 
    @fwrite($fp,"\xFF\xFF\xFF\xFF\x54\x53\x6F\x75\x72\x63\x65\x20\x45\x6E\x67\x69\x6E\x65\x20\x51\x75\x65\x72\x79\x00".chr(10));
    $start=time();
    socket_set_timeout($fp,1);
    $st=fread($fp,1);
    $r=socket_get_status($fp);
    $result['status'] = $r["timed_out"];
    $r=$r["unread_bytes"];
    if ($r == 0) { @fclose($fp); return false;}
    $st.=fread($fp,$r);
    @fclose($fp);
   
    return $result;
}
    $info = GetServerInfo($ip, $port);
        if (!$info) print "Технический статус сервера: <span style='color:red;'>Отключен</span>";
        else print "Технический статус сервера: <span style='color:green;'>Работает</span>";

?>
Добавлено через 6 минут
HooLIGUN, Будет работать, но это не выход, засорять сайт фреймами не стоит.
Теперь все работает. Огроменное тебе спасибо
Только пока он пишет "отключен", хотя сервер работает.

В общем, данные он не получает... как следствие, динамики нет, надпись статична
 
Последнее редактирование:

★Сириус★

Участник
Сообщения
743
Реакции
197
а можно ли в данный скрипт прикрутить еще, чтобы показывало когда включен, сколько игроков играет из доступных слотов?
например:
Технический статус сервера: Работает 5/32
 

Vaio

Участник
Сообщения
625
Реакции
215
а можно ли в данный скрипт прикрутить еще, чтобы показывало когда включен, сколько игроков играет из доступных слотов?
например:
Технический статус сервера: Работает 5/32

lgsl, не? зачем велосипеды писать...
 

TolikCorp

Участник
Сообщения
874
Реакции
334
В LGSL есть хоть кеширование. А тут - каждое новое обращение - это запрос к серву.
 

Webman

Nevermind
Сообщения
803
Реакции
330
Sam_Fisher, Какая игра?
TolikCorp, Поработаю над этим.
★Сириус★,
PHP:
<?php
 
$ip = ""; // IP сервера
$port = ""; // Порт сервера
 
function GetServerInfo($ip,$port) {
   $fp = @fsockopen("udp://".$ip, $port);
   if (!$fp) return false;
 
    @fwrite($fp,"\xFF\xFF\xFF\xFF\x54\x53\x6F\x75\x72\x63\x65\x20\x45\x6E\x67\x69\x6E\x65\x20\x51\x75\x65\x72\x79\x00".chr(10));
    $start=time();
    socket_set_timeout($fp,1);
    $st=fread($fp,1);
    $r=socket_get_status($fp);
    $result['status'] = $r["timed_out"];
    $r=$r["unread_bytes"];
    if ($r == 0) { @fclose($fp); return false;}
    $st.=fread($fp,$r);
    @fclose($fp);


   $st=substr($st,5);
   $address=SubStr($st,0,StrPos($st,chr(0)));
   $address=str_replace(chr(0),"|",$address);
   $st=SubStr($st,StrPos($st,chr(0))+1);
   $name=SubStr($st,0,StrPos($st,chr(0)));
   $st=SubStr($st,StrPos($st,chr(0))+1);
   $map=SubStr($st,0,StrPos($st,chr(0)));
   $st=SubStr($st,StrPos($st,chr(0))+1);
   $st=SubStr($st,StrPos($st,chr(0))+1);
   $st=SubStr($st,StrPos($st,chr(0))+1);
   
   $current=ord(SubStr($st,0,1));
   $max=ord(SubStr($st,1,1));
 
   $result['current'] = $current;
   $result['max'] = $max;
 
   return $result;
}
 
   $info = GetServerInfo($ip, $port);
 
   if(!$info) print "<b>Технический статус сервера: <span style=\"color: red;\">Отключен</span></b>";
   else print "<b>Технический статус сервера: <span style=\"color: green;\">Работает</span> <span style=\"color:blue\">" . $info['current'] . "/" . $info['max'] . "</span></b>";
?>
 

Webman

Nevermind
Сообщения
803
Реакции
330
Sam_Fisher, Со всеми серверами так? Или твой только?
 
Сверху Снизу