XSERVER からサーバー操作できるAPIのお知らせメールが来ていたので、早速、今まで使っていたツールをそれ用に書き換え。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<?php $api_key = '[APIキー]'; $server_id = 'xsvx1023505'; $servername = $server_id.'.xsrv.jp'; $api_base_url = 'https://api.xserver.ne.jp'; $api_base_path = '/v1/server/'.$servername; $target = 'silverfox'; $domain = 'noizumi.org'; $url_ip_prog = 'https://yuji.noizumi.org/ip.php'; $url_ip_txt = 'https://yuji.noizumi.org/ip.txt'; $dns_id = '76684883'; // 作成済のDNSレコードID silverfox.noizumi.org // nslookup から、現在DNSに登録されているIPアドレスを抜き出す。 ob_start(); passthru('nslookup '.$target.'.'.$domain.' ns5.xserver.jp'); $buf = ob_get_clean(); $hosts = ''; if(preg_match_all('/Address:\s+((\d+\.){3}\d+)/',$buf ,$matches)){ $hosts = $matches[1][1]; } // IPv4を明示的に指定して接続するコンテキストを作成 $context = stream_context_create([ 'socket' => [ // IPv4アドレスでバインドする(通常は0.0.0.0:0) 'bindto' => '0.0.0.0:0', ], ]); $response = file_get_contents($url_ip_prog, false, $context); if(preg_match('/Your IP address is ([0-9.]*)/', $response, $matches)){ $myip = $matches[1]; }else{ $myip = file_get_contents($url_ip_txt); } if($myip==$hosts){ exit(0); } $params = array( 'domain' => $domain, 'host' => $target, 'type' => 'A', 'content' => $myip ); $fields = http_build_query($params); $header = array( 'Content-Length: ' . strlen($fields), 'Authorization: Bearer '.$api_key ); $ch = curl_init(); //curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); // IPv4 Only. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // HTTPレスポンス 30x を追跡する。 curl_setopt($ch, CURLOPT_HEADER, false); $command = '/dns/'.$dns_id; curl_setopt($ch, CURLOPT_URL, $api_base_url.$api_base_path.$command); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); ?> |
asahiネットにプロバイダ変更して、IPv6環境になり、XSERVER以外のサーバーにアクセスすると、IPv6のアドレスが記録されちゃうので、file_get_contents()で、明示的にIPv4でアクセスするようにしてある。
次のプログラムは、XSERVERに置いておいて、家のサーバーからアクセスすると、家の回線のIPv4アドレスが分かるやつ。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$ip = $_SERVER['REMOTE_ADDR']; file_put_contents( 'ip.txt', $ip ); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>IP address</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="generator" content="Geany 1.27" /> </head> <body> Your IP address is <?php echo $ip ?> </body> </html> |
VPNで家のサーバーに接続する際に、家の回線はIPアドレス固定じゃないので、ルーター再起動したりすると、IPアドレスが変わってしまう。
その為、家のサーバーで、5分おきに ipcheck.php を走らせて、DNS情報と、実際のIPアドレスに相違があるかをチェックしていて、違っていたら、XSERVERのDNSをAPIで変更するようになっている。
