Skip to content
This repository has been archived by the owner on Oct 13, 2024. It is now read-only.

Commit

Permalink
fix(helpers): properly check public status of IPv6 addresses (#266)
Browse files Browse the repository at this point in the history
  • Loading branch information
ReenigneArcher authored May 27, 2023
1 parent 47b9fb1 commit fec9b6e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
16 changes: 11 additions & 5 deletions pyra/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

# standard imports
import datetime
import ipaddress
import logging
import re
import os
Expand Down Expand Up @@ -165,12 +166,16 @@ def is_public_ip(host: str) -> bool:
False
"""
ip = is_valid_ip(address=get_ip(host=host))
if ip and ip.iptype() == 'PUBLIC':
return True
return False

# use built in ipaddress module to check if address is private since IPy does not work IPv6 addresses
if ip:
ip_obj = ipaddress.ip_address(address=ip)
return not ip_obj.is_private
else:
return False


def get_ip(host: str) -> str:
def get_ip(host: str) -> Optional[str]:
"""
Get IP address from host name.
Expand All @@ -184,7 +189,7 @@ def get_ip(host: str) -> str:
Returns
-------
str
IP address of host name.
IP address of host name if it is a valid ip address, otherwise ``None``.
Examples
--------
Expand All @@ -201,6 +206,7 @@ def get_ip(host: str) -> str:
ip_address = socket.getaddrinfo(host=host, port=None)[0][4][0]
except Exception:
log.error(f"IP Checker :: Bad IP or hostname provided: {host}.")
return None
else:
log.debug(f"IP Checker :: Resolved {host} to {ip_address}.")
return ip_address
Expand Down
36 changes: 25 additions & 11 deletions tests/unit/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,31 @@ def test_get_logger():


def test_is_public_ip():
"""Test if ip address is pubic, then tests if ip address is private"""
# test public ip
address = 'www.google.com'
ip = helpers.get_ip(host=address)
public_ip = helpers.is_public_ip(host=ip)
assert public_ip

# test private ip
ip = '192.168.1.1'
public_ip = helpers.is_public_ip(host=ip)
assert not public_ip
"""Test if ip address is pubic or private"""
# test public ips
public_addresses = [
'www.google.com',
'8.8.8.8',
'8.8.4.4',
'2001:4860:4860::8888',
'2001:4860:4860::8844',
]

private_addresses = [
'192.168.1.1'
]

address_types = [public_addresses, private_addresses]

for address_type in address_types:
for address in address_type:
ip = helpers.get_ip(host=address)
public_ip = helpers.is_public_ip(host=ip)

if address_type == public_addresses:
assert public_ip
else:
assert not public_ip


def test_get_ip():
Expand Down

0 comments on commit fec9b6e

Please sign in to comment.