2022年3月30日 星期三

自建 DDNS 轉址

由於 HiNet 只提供一個固定 IP, 只能給一個路由器使用, 如果另一個路由器用 PPPOE 取得浮動 IP, 可透過這個固定 IP 下的網站來進行轉址. 本例中, 浮動 IP 端使用樹莓派當伺服器, 使用 python3 環境, 固定 IP 端為一般 PC, 安裝 xampp (apache+php+mysql).

PC端在 htdocs 下建立一個 smartcenter 目錄, 放3個 php 檔

set_ip.php:  設定 ddns ip

<?php

        $host =  htmlspecialchars($_GET["HOST"]);

        $ip = htmlspecialchars($_GET["IP"]);

        $filename = "ip.".$host; 

        $file = fopen($filename,"w");

        fwrite($file,$ip);

        fclose($file);

?>

 get_ip:php: 回傳 ddns ip

<?php

        $host =  htmlspecialchars($_GET["HOST"]);

        $filename = "ip.".$host;

        if (file_exists($filename))

        {

                $file = fopen($filename,"r");

                $ip = fread($file,filesize($filename));

                fclose($file);

        } else {

                $ip="0";

        }

        echo '{"IP":"'.$ip.'"}';

?>

 index.php: 轉址

<?php

        $filename = "ip.smartcenter";

        if (file_exists($filename))

        {

                $file = fopen($filename,"r");

                $ip = fread($file,filesize($filename));

                fclose($file);

        } else {

                $ip="0";

        }

       

    header('Location: http://'.$ip);

?>

樹莓派的 set_ddns_ip.py 程式: 先取得外部 ip, 呼叫 set_ip.php 進行設定, 再呼叫 get_ip.php 檢查結果:

#!python3

import requests

r =requests.get('https://api.myip.com/')

print(r.status_code)

print(r.text)

 

#print(r.json())

my_ip=r.json()['ip']

print('my_ip="'+my_ip+'"')

 

ddns_server='http://自己的網址'

host='smartcenter'

args = {'HOST':host,'IP':my_ip}

r = requests.get(ddns_server+'/smartcenter/set_ip.php',params=args)

#print(r.status_code)

#print(r.text)

 

 

args = {'HOST':host}

r = requests.get(ddns_server+'/smartcenter/get_ip.php',params=args)

#print(r.status_code)

registered_ip=r.json()['IP']

print('registered_ip="'+registered_ip+'"')

 

if(registered_ip!=my_ip):

    print("Bad")

else:

    print("OK");

 建立一個 /set_ddns_ip.sh

 

 然後只要設定 crontab 每分鐘自動更新即可:

# m h  dom mon dow   command

* * * * * /home/pi/set_ddns_ip.sh

 

 瀏覽器只要使用原先的網址, 例如 http://自己的網址/smartcenter, 即可自動轉址