From 59bde2bfe426150622dfed3c22395aad92743c0f Mon Sep 17 00:00:00 2001
From: Nicolas KAROLAK <nicolas@karolak.fr>
Date: Wed, 1 May 2019 08:11:04 +0200
Subject: [PATCH] get primary ip address | refs #28817

---
 tests/test_email.py |  3 ++-
 utils.py            | 20 ++++++++++++++++++++
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/tests/test_email.py b/tests/test_email.py
index 2a1ccfea..786e564a 100755
--- a/tests/test_email.py
+++ b/tests/test_email.py
@@ -179,7 +179,7 @@ def check_spf(ip_addr: str, sender: str, domain: str) -> tuple:
     errors = 0
 
     if ip_address(ip_addr).is_private:
-        u.info("{} is a private address, cannot check SPF")
+        u.info("{} is a private address, cannot check SPF".format(ip_addr))
     elif ip_addr and sender:
         # check spf
         result, _ = spf.check2(i=ip_addr, s=domain, h="")
@@ -215,6 +215,7 @@ def main():
         (socket.gethostbyname(relay) if relay else None)
         or conf.get("NETWORK_IP_NAT")
         or conf.get("NETWORK_IP")
+        or u.get_ip()
         or None
     )
     sender = conf.get("EMAIL_SENDER") or None
diff --git a/utils.py b/utils.py
index 3f26783e..15399fe2 100644
--- a/utils.py
+++ b/utils.py
@@ -449,3 +449,23 @@ def mkcert(
             cert_dir + "/cert.pem",
         ]
     )
+
+
+def get_ip() -> str:
+    """Get the "primary" ip address, the one used by the default route.
+
+    :return: IP address
+    :rtype: str
+    """
+
+    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+    try:
+        # doesn't have to be reachable
+        s.connect(("10.255.255.255", 1))
+        IP = s.getsockname()[0]
+    except Exception:
+        IP = "127.0.0.1"
+    finally:
+        s.close()
+
+    return IP
-- 
GitLab