Skip to content

Commit

Permalink
feat(utils): add get_public_ip_addresses function (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
andre8244 authored Nov 20, 2024
1 parent e460e7f commit 52bb06c
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/nethsec/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,38 @@ def get_all_wan_ips(uci):

return sorted(ret, key=lambda k: k['ipaddr'])


def get_public_ip_addresses(ip_address=""):
"""
Return the public addresses associated to a private IP address.
Arguments:
- ip_address -- the private IP address of a network interface. If not specified, the default network interface is used.
Returns:
- a list of public addresses. Usually, the list contains only one element.
"""
try:
bindOption = ""
if ip_address:
bindOption = f" -b {ip_address}"

cmd = f"/usr/bin/dig{bindOption} +short +time=1 myip.opendns.com @resolver1.opendns.com".split(" ")
output = subprocess.check_output(cmd, timeout=5)
public_ip_addresses = output.decode().strip().split('\n')

if public_ip_addresses[0] == "":
# cannot retrieve public IP address, returning input IP address as fallback
if ip_address:
return [ip_address]
else:
return []
else:
return public_ip_addresses
except Exception as e:
return []


class ValidationError(ValueError):
def __init__(self, parameter, message="", value=""):
self.parameter = parameter
Expand Down

0 comments on commit 52bb06c

Please sign in to comment.