Skip to content

Instantly share code, notes, and snippets.

@anon5r
Last active October 10, 2016 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anon5r/041a5c918650efa69cdbeb87bd649ed4 to your computer and use it in GitHub Desktop.
Save anon5r/041a5c918650efa69cdbeb87bd649ed4 to your computer and use it in GitHub Desktop.
$hostname の $port が接続先としてコネクション応答出来る状態かを確認します。
<?php
/**
* $hostname が接続先として接続応答出来る状態かを確認します。
*
* @access public
* @static
* @param string $hostname 接続先ホスト名またはIP
* @param int $port 接続先ポート番号
* @param int $timeout タイムアウトを指定する(秒)
* @return boolean
*/
function isAliveHost($hostname, $port = 80, $timeout = 5)
{
if (empty($hostname)) {
if (version_compare(PHP_VERSION, '5.0.0', '< ')) {
trigger_error('Hostname is empty.', E_USER_ERROR);
} else {
throw new Exception('Hostname is empty.');
}
}
// port番号指定がint型以外、あるいはintの範囲外である場合はfalseを返します。
if (!is_int($port)) {
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
trigger_error('Invalid port number: ' . $port, E_USER_ERROR);
} else {
throw new Exception('Invalid port number: ' . $port);
}
}
// port番号が65535を超える場合は、不正な値とみなし、falseを返します。
if ($port < 0 || $port > 65535) {
if (version_compare(PHP_VERSION, '5.0.0', '< ')) {
trigger_error('Invalid range of port number: ' . $port, E_USER_ERROR); // for PHP4
} else {
throw new Exception('Invalid range of port number: ' . $port);
}
}
$fp = fsockopen($hostname, $port, $errno, $errmsg, $timeout);
if (!$fp) {
error_log('could not connect to ' . $hostname . ':' . $port . ', ' . $errmsg);
return false;
}
fclose($fp);
return true;
}
@anon5r
Copy link
Author

anon5r commented Oct 10, 2016

もう7年くらい前に書いたコード

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment