接続先のサーバが応答するか判別する

PHPのプログラム中で、別のサーバに接続する際、タイムアウトを適切に設定していない場合や、データ取得時にタイムアウトを設定できない場合もあるかと思います。そんなときに、まず先に接続先が生存しているかを確認しておくと、エラー処理の判定もしやすくなると思います。

そこで、接続を開始する前に事前に接続先のサーバに接続を試行してみます。

※PHP5.0以前の環境ではこのまま実行すると、throwの部分で構文エラーになる可能性があります。その場合はバージョン判定部分とthrow new Exceptionの部分を取り除いてください。


PHP:
  1. /**
  2. * $hostname が接続先として接続応答出来る状態かを確認します。
  3. *
  4. * @access public static
  5. * @param string $hostname 接続先ホスト名またはIP
  6. * @param int $port 接続先ポート番号
  7. * @param int $timeout タイムアウトを指定する(秒)
  8. * @return boolean
  9. */
  10. function isAliveHost($hostname, $port = 80, $timeout = 5)
  11. {
  12.     if(empty($hostname)){
  13.         if(version_compare(PHP_VERSION, '5.0.0', '<')){
  14.             trigger_error('Hostname is empty.', E_USER_ERROR);
  15.         }else{
  16.             throw new Exception('Hostname is empty.');
  17.         }
  18.     }
  19.    
  20.     // port番号指定がint型以外、あるいはintの範囲外である場合はfalseを返します。
  21.     if(!is_int($port)){
  22.         if(version_compare(PHP_VERSION, '5.0.0', '<')){
  23.             trigger_error('Invalid port number: ' . $port, E_USER_ERROR);
  24.         }else{
  25.             throw new Exception('Invalid port number: ' . $port);
  26.         }
  27.     }
  28.    
  29.     // port番号が65535を超える場合は、不正な値とみなし、falseを返します。
  30.     if($port <0 || $port> 65535){
  31.         if(version_compare(PHP_VERSION, '5.0.0', '<')){
  32.             trigger_error('Invalid range of port number: ' . $port, E_USER_ERROR);    // for PHP4
  33.         }else{
  34.             throw new Exception('Invalid range of port number: ' . $port);
  35.         }
  36.     }
  37.    
  38.     $fp = fsockopen($hostname, $port, $errno, $errmsg, $timeout);
  39.     if(!$fp){
  40.         error_log('could not connect to ' . $hostname . ':' . $port . ', ' . $errmsg);
  41.         return false;
  42.     }
  43.     fclose($fp);
  44.    
  45.     return true;
  46.    
  47. }



使い方は以下の通り




PHP:
  1. <?php
  2. if(isAliveHost('www.google.co.jp', 80)){
  3.     $content = file_get_contents('http://www.google.co.jp/');
  4. }else{
  5.     error_log('failed to get index page on www.google.co.jp.');
  6. }





PHP:
  1. <?php
  2. if(!isAliveHost('mfsmax.docomo.ne.jp', 25)){
  3.     error_log('failed to connect to port 25 on docomo.ne.jp.');
  4. }

No TweetBacks yet. (Be the first to Tweet this post)

Related posts:

  1. PreparedなINSERT文を簡単に作る方法 PHPでWebアプリケーションなどを開発していて、SQL文を発行する際に、セキュア面や利便性などから、ADODBやPDOなどを用いて、Prepared Statementを使うSQLを書くこともあると思います。 その [...]...

関連記事はYARPP関連記事プラグインによって表示されています。

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes