mirror of
https://github.com/jlu5/PyLink.git
synced 2024-11-27 04:59:24 +01:00
utils: add get_hostname_type() to autodetect address types (#212)
This commit is contained in:
parent
040b009fcb
commit
5ea33baa8e
@ -130,5 +130,25 @@ class UtilsTestCase(unittest.TestCase):
|
||||
utils.remove_range(
|
||||
"-3--5", ["we", "love", "emotes"])
|
||||
|
||||
def test_get_hostname_type(self):
|
||||
self.assertEqual(utils.get_hostname_type("1.2.3.4"), 1)
|
||||
self.assertEqual(utils.get_hostname_type("192.168.0.1"), 1)
|
||||
self.assertEqual(utils.get_hostname_type("127.0.0.5"), 1)
|
||||
|
||||
self.assertEqual(utils.get_hostname_type("0::1"), 2)
|
||||
self.assertEqual(utils.get_hostname_type("::1"), 2)
|
||||
self.assertEqual(utils.get_hostname_type("fc00::1234"), 2)
|
||||
self.assertEqual(utils.get_hostname_type("1111:2222:3333:4444:5555:6666:7777:8888"), 2)
|
||||
|
||||
self.assertEqual(utils.get_hostname_type("example.com"), False)
|
||||
self.assertEqual(utils.get_hostname_type("abc.mynet.local"), False)
|
||||
self.assertEqual(utils.get_hostname_type("123.example"), False)
|
||||
|
||||
self.assertEqual(utils.get_hostname_type("123.456.789.000"), False)
|
||||
self.assertEqual(utils.get_hostname_type("1::2::3"), False)
|
||||
self.assertEqual(utils.get_hostname_type("1:"), False)
|
||||
self.assertEqual(utils.get_hostname_type(":5"), False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
18
utils.py
18
utils.py
@ -11,6 +11,7 @@ import importlib
|
||||
import os
|
||||
import collections
|
||||
import argparse
|
||||
import ipaddress
|
||||
|
||||
from .log import log
|
||||
from . import world, conf, structures
|
||||
@ -750,3 +751,20 @@ def remove_range(rangestr, mylist):
|
||||
(subrange, rangestr))
|
||||
|
||||
return list(filter(lambda x: x is not None, mylist))
|
||||
|
||||
def get_hostname_type(address):
|
||||
"""
|
||||
Returns whether the given address is an IPv4 address (1), IPv6 address (2), or neither
|
||||
(False; assumed to be a hostname instead).
|
||||
"""
|
||||
try:
|
||||
ip = ipaddress.ip_address(address)
|
||||
except ValueError:
|
||||
return False
|
||||
else:
|
||||
if isinstance(ip, ipaddress.IPv4Address):
|
||||
return 1
|
||||
elif isinstance(ip, ipaddress.IPv6Address):
|
||||
return 2
|
||||
else:
|
||||
raise ValueError("Got unknown value %r from ipaddress.ip_address()" % address)
|
||||
|
Loading…
Reference in New Issue
Block a user