2014-02-28 23:12:34 +00:00
|
|
|
# Copyright (C) 2003-2014 Bastian Kleineidam
|
2009-02-18 15:33:52 +00:00
|
|
|
#
|
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
|
# (at your option) any later version.
|
|
|
|
|
#
|
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
|
#
|
2009-07-24 21:58:20 +00:00
|
|
|
# You should have received a copy of the GNU General Public License along
|
|
|
|
|
# with this program; if not, write to the Free Software Foundation, Inc.,
|
|
|
|
|
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
2009-02-18 15:33:52 +00:00
|
|
|
"""
|
|
|
|
|
Ip number related utility functions.
|
|
|
|
|
"""
|
|
|
|
|
|
2020-03-31 18:46:31 +00:00
|
|
|
import ipaddress
|
2009-02-18 15:33:52 +00:00
|
|
|
import re
|
|
|
|
|
import socket
|
2011-05-24 18:18:58 +00:00
|
|
|
from .. import log, LOG_CHECK
|
2009-02-18 15:33:52 +00:00
|
|
|
|
2020-05-30 16:01:36 +00:00
|
|
|
|
2020-05-16 19:19:42 +00:00
|
|
|
def is_valid_ip(ip):
|
2009-02-18 15:33:52 +00:00
|
|
|
"""
|
|
|
|
|
Return True if given ip is a valid IPv4 or IPv6 address.
|
|
|
|
|
"""
|
2020-03-31 18:46:31 +00:00
|
|
|
try:
|
|
|
|
|
ipaddress.ip_address(ip)
|
|
|
|
|
except ValueError:
|
2009-02-18 15:33:52 +00:00
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
2020-05-16 19:19:42 +00:00
|
|
|
def resolve_host(host):
|
2009-02-18 15:33:52 +00:00
|
|
|
"""
|
2014-02-28 23:12:34 +00:00
|
|
|
Return list of ip numbers for given host.
|
2020-07-25 15:35:48 +00:00
|
|
|
|
|
|
|
|
@param host: hostname or IP address
|
2009-02-18 15:33:52 +00:00
|
|
|
"""
|
2014-02-28 23:12:34 +00:00
|
|
|
ips = []
|
2009-02-18 15:33:52 +00:00
|
|
|
try:
|
|
|
|
|
for res in socket.getaddrinfo(host, None, 0, socket.SOCK_STREAM):
|
|
|
|
|
# res is a tuple (address family, socket type, protocol,
|
|
|
|
|
# canonical name, socket address)
|
|
|
|
|
# add first ip of socket address
|
2014-02-28 23:12:34 +00:00
|
|
|
ips.append(res[4][0])
|
2009-02-18 15:33:52 +00:00
|
|
|
except socket.error:
|
2011-05-24 18:18:58 +00:00
|
|
|
log.info(LOG_CHECK, "Ignored invalid host %r", host)
|
2009-02-18 15:33:52 +00:00
|
|
|
return ips
|
2010-09-05 18:11:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
is_obfuscated_ip = re.compile(r"^(0x[a-f0-9]+|[0-9]+)$").match
|