From d6949f7a5bddc7aa6d192d8155040c83f7f583fb Mon Sep 17 00:00:00 2001
From: arjuan <rmarchant+github@gmail.com>
Date: Thu, 6 Apr 2017 19:05:12 +0000
Subject: [PATCH] add ipaddress validation

---
 README.md     |  4 ++++
 gandi-ddns.py | 10 ++++++++--
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/README.md b/README.md
index d971c40..af3ad58 100644
--- a/README.md
+++ b/README.md
@@ -5,3 +5,7 @@ http://doc.livedns.gandi.net/
 The config-template.txt file should be renamed to config.txt, and modified with your gandi.net API key, domain name, and A-record (@, dev, home, pi, etc).
 
 Every time the script runs, it will query an external service to retrieve the external IP of the machine, compare it to the current record (if any) in the zone at gandi.net, and then add a new record (if none currently exists), or delete then add a new record (if a record already exists).
+
+Requirements:
+  - Python 2.7
+  - ipaddress module (pip install ipaddress)
diff --git a/gandi-ddns.py b/gandi-ddns.py
index a1a29d4..ae6a3e9 100644
--- a/gandi-ddns.py
+++ b/gandi-ddns.py
@@ -3,6 +3,7 @@ import sys
 import os
 import requests
 import json
+import ipaddress
 
 config_file = "config.txt"
 
@@ -20,7 +21,12 @@ def get_ip():
           print('Failed to retrieve external IP. Server responded with status_code: %d' % result.status_code)
           sys.exit(2)
 
-        return r.text
+        ip = r.text.rstrip() # strip \n and any trailing whitespace
+
+	if not(ipaddress.IPv4Address(ip)): # check if valid IPv4 address
+          sys.exit(2)
+
+        return ip
 
 def read_config(config_path):
         #Read configuration file
@@ -79,7 +85,7 @@ def main():
     url = '%sdomains/%s/records/%s/A' % (config.get(section, "api"), config.get(section, "domain"), config.get(section, "a_name"))
     print(url)
     #Discover External IP
-    external_ip = get_ip()[0:-1]
+    external_ip = get_ip()
     print("external IP is: %s" % external_ip)
 
     #Prepare record
-- 
GitLab