Skip to content

Instantly share code, notes, and snippets.

@hugozhu
Last active August 19, 2022 06:19
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save hugozhu/4268277 to your computer and use it in GitHub Desktop.
Save hugozhu/4268277 to your computer and use it in GitHub Desktop.
动态根据宽带public ip更新dnspod登记的域名,按照 https://gist.github.com/833369 逻辑重新用Go实现了,用更少的内存开销在Raspberry Pi上跑 替换上你的Email,密码,域名ID,记录ID等参数,就可以运行了。 会在后台一直运行,每隔30秒检查一遍IP,如果修改了就更新IP。 获得domain_id可以用curl curl -k https://dnsapi.cn/Domain.List -d "login_email=xxx&login_password=xxx" 获得record_id类似 curl -k https://dnsapi.cn/Record.List -d "login_email=xxx&login_passwo…
package main
import (
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
)
var (
body = url.Values{
"login_email": {"email"},
"login_password": {"password"},
"format": {"json"},
"domain_id": {"0"},
"record_id": {"0"},
"sub_domain": {"www"},
"record_line": {"默认"},
}
current_ip = ""
check_interval = 30 * time.Second
)
func get_public_ip() (string, error) {
conn, err := net.DialTimeout("tcp", "ns1.dnspod.net:6666", timeout*time.Second)
defer func() {
if x := recover(); x != nil {
log.Println("Can't get public ip", x)
}
if conn!=nil {
conn.Close()
}
}()
if err == nil {
deadline := time.Now().Add(timeout*time.Second)
err = conn.SetDeadline(deadline)
if err!=nil {
return "", err
}
var bytes []byte
bytes, err = ioutil.ReadAll(conn)
if err == nil {
return string(bytes), nil
}
}
return "", err
}
func update_dnspod(ip string) bool {
client := new(http.Client)
body.Set("value", ip)
req, err := http.NewRequest("POST", "https://dnsapi.cn/Record.Ddns", strings.NewReader(body.Encode()))
req.Header.Set("Accept", "text/json")
req.Header.Set("Content-type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return false
}
bytes, _ := ioutil.ReadAll(resp.Body)
log.Println(string(bytes))
return resp.StatusCode == 200
}
func main() {
for {
ip, err := get_public_ip()
if err == nil {
if ip != current_ip {
if update_dnspod(ip) {
current_ip = ip
}
}
}
time.Sleep(check_interval)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment