From 344b056a6d6fc2b3620bd9808fcc8d0b9a84be0c Mon Sep 17 00:00:00 2001 From: root Date: Wed, 16 Dec 2020 18:01:40 +0800 Subject: [PATCH] use cloudflare trace & force it to be ipv4/ipv6 --- cloudflare-ddns.py | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/cloudflare-ddns.py b/cloudflare-ddns.py index 65a1824..9ffbc5b 100755 --- a/cloudflare-ddns.py +++ b/cloudflare-ddns.py @@ -1,3 +1,5 @@ +import socket +import requests.packages.urllib3.util.connection as urllib3_cn import requests, json, sys, os import time @@ -10,15 +12,40 @@ if(version < 3.5): with open(PATH + "config.json") as config_file: config = json.loads(config_file.read()) +def allowed_gai_family6(): + family = socket.AF_INET + if urllib3_cn.HAS_IPV6: + family = socket.AF_INET6 # force ipv6 only if it is available + return family + +def allowed_gai_family4(): + family = socket.AF_INET + return family + def getIPs(): a = "" aaaa = "" try: - a = requests.get("https://dns.timknowsbest.com/api/ipv4").text - except Exception: + urllib3_cn.allowed_gai_family = allowed_gai_family4 + a = requests.get("https://www.cloudflare.com/cdn-cgi/trace").text.split("\n") + a.pop() + ajson = json.loads("{}") + for value in a: + value = value.split("=") + ajson[value[0]] = value[1] + a = ajson['ip'] + except Exception as e: + print(e) print("Warning: IPv4 not detected.") try: - aaaa = requests.get("https://api6.ipify.org?format=json").json().get("ip") + urllib3_cn.allowed_gai_family = allowed_gai_family6 + aaaa = requests.get("https://www.cloudflare.com/cdn-cgi/trace").text.split("\n") + aaaa.pop() + aaaajson = json.loads("{}") + for value in aaaa: + value = value.split("=") + aaaajson[value[0]] = value[1] + aaaa = aaaajson['ip'] except Exception: print("Warning: IPv6 not detected.") ips = [] @@ -134,4 +161,4 @@ if(len(sys.argv) > 1): else: print("Unrecognized parameter '" + sys.argv[1] + "'. Stopping now.") else: - updateIPs() \ No newline at end of file + updateIPs()