From 285b320ea5d27050ac3f12595f50dbcea8a4f964 Mon Sep 17 00:00:00 2001 From: Kevin Chung Date: Fri, 9 Jun 2017 22:23:24 -0400 Subject: [PATCH] Switching to netaddr because ip address parsing is hard (#275) This also re-adds Windows support --- CTFd/models.py | 18 ++++-------------- requirements.txt | 1 + 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/CTFd/models.py b/CTFd/models.py index daab74f..a1ff78e 100644 --- a/CTFd/models.py +++ b/CTFd/models.py @@ -1,6 +1,7 @@ import datetime import hashlib import json +import netaddr from socket import inet_pton, inet_ntop, AF_INET, AF_INET6 from struct import unpack, pack, error as struct_error @@ -15,23 +16,12 @@ def sha512(string): def ip2long(ip): '''Converts a user's IP address into an integer/long''' - if '.' in ip: - # ipv4 - return unpack('!i', inet_pton(AF_INET, ip))[0] - else: - # ipv6 - hi, lo = unpack('!QQ', inet_pton(AF_INET6, ip)) - return (hi << 64) | lo + return int(netaddr.IPAddress(ip)) def long2ip(ip_int): - '''Converts a saved IP address back into an integer/long''' - if ip_int < 4294967296: - # ipv4 - return inet_ntop(AF_INET, pack('!i', ip_int)) - else: - # ipv6 - return inet_ntop(AF_INET6, pack('!QQ', ip_int >> 64, ip_int & 0xffffffffffffffff)) + '''Converts a saved integer/long back into an IP address''' + return str(netaddr.IPAddress(ip_int)) db = SQLAlchemy() diff --git a/requirements.txt b/requirements.txt index 1788766..2833994 100644 --- a/requirements.txt +++ b/requirements.txt @@ -14,3 +14,4 @@ PyMySQL==0.7.10 gunicorn==19.7.0 dataset==0.8.0 mistune==0.7.4 +netaddr==0.7.19