new check_ip() validates if a str is a ip addr and also determines address family, deduplicate code

This commit is contained in:
Thomas Waldmann 2013-10-03 20:39:55 +02:00
parent 824d77da89
commit 2982bd6e30
3 changed files with 15 additions and 15 deletions

View File

@ -5,8 +5,6 @@ import os
import logging
logger = logging.getLogger(__name__)
import dns.inet
from django.http import HttpResponse
from django.conf import settings
from django.contrib.auth.hashers import check_password
@ -14,7 +12,7 @@ from django.contrib.auth.decorators import login_required
from django.contrib.sessions.backends.db import SessionStore
from main.models import Host
from main.dnstools import update, SameIpError
from main.dnstools import update, SameIpError, check_ip
def Response(content):
@ -51,8 +49,7 @@ def DetectIpView(request, secret=None):
# the secret:
s = SessionStore(session_key=secret)
ipaddr = request.META['REMOTE_ADDR']
af = dns.inet.af_for_address(ipaddr)
key = 'ipv4' if af == dns.inet.AF_INET else 'ipv6'
key = check_ip(ipaddr)
s[key] = ipaddr
s.save()
with open(os.path.join(settings.STATIC_ROOT, "1px.gif"), "rb") as f:

View File

@ -22,15 +22,19 @@ class SameIpError(ValueError):
"""
def get_rdtype(ipaddr):
def check_ip(ipaddr, keys=('ipv4', 'ipv6')):
"""
Get the record type 'A' or 'AAAA' for this ipaddr.
Check if a string is a valid ip address and also
determine the kind of the address (address family).
Return first key for v4, second key for v6.
:param ipaddr: ip address v4 or v6 (str)
:return: 'A' or 'AAAA'
:param ipaddr: ip address, v4 or v6, str
:param keys: 2-tuple (v4key, v6key)
:return: v4key or v6key
:raises: ValueError if the ip is invalid
"""
af = dns.inet.af_for_address(ipaddr)
return 'A' if af == dns.inet.AF_INET else 'AAAA'
return keys[af == dns.inet.AF_INET6]
def add(fqdn, ipaddr, ttl=60):
@ -44,7 +48,7 @@ def add(fqdn, ipaddr, ttl=60):
:param ttl: time to live, default 60s (int)
:raises: SameIpError if new and old IP is the same
"""
rdtype = get_rdtype(ipaddr)
rdtype = check_ip(ipaddr, keys=('A', 'AAAA'))
try:
current_ipaddr = query_ns(fqdn, rdtype)
# check if ip really changed
@ -89,7 +93,7 @@ def update(fqdn, ipaddr, ttl=60):
:param ttl: time to live, default 60s (int)
:raises: SameIpError if new and old IP is the same
"""
rdtype = get_rdtype(ipaddr)
rdtype = check_ip(ipaddr, keys=('A', 'AAAA'))
try:
current_ipaddr = query_ns(fqdn, rdtype)
# check if ip really changed

View File

@ -57,10 +57,9 @@ class HomeView(TemplateView):
context = super(HomeView, self).get_context_data(*args, **kwargs)
context['nav_home'] = True
s = self.request.session
ipaddr = self.request.META['REMOTE_ADDR']
af = dns.inet.af_for_address(ipaddr)
key = 'ipv4' if af == dns.inet.AF_INET else 'ipv6'
key = dnstools.check_ip(ipaddr)
s = self.request.session
s[key] = ipaddr
s.save()