Jump to content
Дизайн и модификация IPS Community IPBSkinsBETA
Search In
  • More options...
Find results that contain...
Find results in...
Sign in to follow this  
TemKa_SD

Перебор портов и вывод свободного

Recommended Posts

Здравствуйте. Написал вот такие функции:

 

protected function checkPort($port)
{
	$connection = @fsockopen( "212.109.217.193", $port, $errno, $errstr );

	if ( $errno != "111")
	{
		$port = $port + 1;
	}

	return $port;
}

protected function getBotPort()
{
	$lastport = \IPS\Db::i()->select( 'MAX(cfg_value)', static::$cfgTable, array('cfg_name=?', 'bot_hostport') )->first();

	if ($lastport) {
		$port = $lastport + 1;
	}
	else
	{
		$port = $port;
	}

	return $this->checkPort(6116);
}

 

В форме стандартное значение функция getBotPort().

 

Логика следующая: Выбираем порты которые уже есть в базе данных, добавляем + 1 и возвращаем результат в функцию проверки порта на свободность. Есть порт занят - сейчас я еще просто +1 добавил, но нужно сделать перебор наверно, пока не найдет свободный порт. Подскажите, с чего начать? Это же foreach нужен?

Share this post


Link to post

Нет, foreach для обхода массива (или iterable объектов) а тут нужен while - выполнять цикл пока условие не будет истинное.

 

protected function checkPort($port)
{
	$connection = @fsockopen( "212.109.217.193", $port, $errno, $errstr );

	return ( $errno == "111" ) ? $port : false;
}

protected function getBotPort()
{
	$lastport = \IPS\Db::i()->select( 'MAX(cfg_value)', static::$cfgTable, array('cfg_name=?', 'bot_hostport') )->first();

	do{
		$port = $this->checkPort( $lastport++ );
	}
	while( !$port );

	return $port;
}

Share this post


Link to post

Спасибки, работает )

 

Два занятых порта: http://prntscr.com/njajsn

Указываем первый: http://prntscr.com/njajww

 

Результат: http://prntscr.com/njajzm

 

Только надо добавить, чтобы поиск производился с 6112, если отсутствуют записи в БД, а если есть в БД - добавлять + 1, вдруг бот отключен и порт будет свободен, а на самом деле он уже зарезервирован.

 

protected function checkPort($port)
{
   $connection = @fsockopen( "212.109.217.193", $port, $errno, $errstr );

   return ( $errno == "111" ) ? $port : false;
}

protected function getBotPort()
{
   $lastport = \IPS\Db::i()->select( 'MAX(cfg_value)', static::$cfgTable, array('cfg_name=?', 'bot_hostport') )->first();
   $lastport = $lastport ? $lastport + 1 : 6112;

   do{
       $port = $this->checkPort( $lastport++ );
   }
   while( !$port );

   return $port;
}

 

Скажите, а зачем тут в скобках? Оно ведь и так будет работать.

 

return ( $errno == "111" ) ? $port : false;

Edited by TemKa_SD

Share this post


Link to post

Будет работать. Скобки тут для удобо-читаемости кода.

Share this post


Link to post

Здравствуйте, я пару дней назад пробовал реализовать для udp порта тоже самое, но оно почему-то не работает, и вот здесь у меня пишет udp6, может это другой протокол?

 

http://prntscr.com/nndkgm

 

Т.е там всегда писало что порт свободен, не было ошибок.

Edited by TemKa_SD

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...