codekingpro/portable-devtools
114k
1""" Utilities and constants related to reverse dns lookup """2 3# Created on 2020.09.164#5# Author: Azaria Zornberg6#7# Copyright 2020 Giovanni Cannata8# Copyright 2020 Azaria Zornberg9#10# This file is part of ldap3.11#12# ldap3 is free software: you can redistribute it and/or modify13# it under the terms of the GNU Lesser General Public License as published14# by the Free Software Foundation, either version 3 of the License, or15# (at your option) any later version.16#17# ldap3 is distributed in the hope that it will be useful,18# but WITHOUT ANY WARRANTY; without even the implied warranty of19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the20# GNU Lesser General Public License for more details.21#22# You should have received a copy of the GNU Lesser General Public License23# along with ldap3 in the COPYING and COPYING.LESSER files.24# If not, see <http://www.gnu.org/licenses/>.25 26import socket27 28 29class ReverseDnsSetting(object):30 OFF = 0,31 REQUIRE_RESOLVE_ALL_ADDRESSES = 1,32 REQUIRE_RESOLVE_IP_ADDRESSES_ONLY = 2,33 OPTIONAL_RESOLVE_ALL_ADDRESSES = 3,34 OPTIONAL_RESOLVE_IP_ADDRESSES_ONLY = 4,35 SUPPORTED_VALUES = {OFF, REQUIRE_RESOLVE_ALL_ADDRESSES, REQUIRE_RESOLVE_IP_ADDRESSES_ONLY,36 OPTIONAL_RESOLVE_ALL_ADDRESSES, OPTIONAL_RESOLVE_IP_ADDRESSES_ONLY}37 38 39def get_hostname_by_addr(addr, success_required=True):40 """ Resolve the hostname for an ip address. If success is required, raise an exception if a hostname cannot41 be resolved for the address.42 Returns the hostname resolved for the address.43 If success is not required, returns None for addresses that do not resolve to hostnames.44 """45 try:46 return socket.gethostbyaddr(addr)[0]47 except Exception as ex:48 # if we need to succeed, just re-raise49 if success_required:50 raise51 return None52 53 54def is_ip_addr(addr):55 """Returns True if an address is an ipv4 address or an ipv6 address based on format. False otherwise."""56 for addr_type in [socket.AF_INET, socket.AF_INET6]:57 try:58 socket.inet_pton(addr_type, addr) # not present on python 2.7 on Windows59 return True60 except AttributeError: # not present on Windows, always valid61 if '.' in addr and any([c.isalpha() for c in addr.replace('.', '')]): # not an IPv4 address, probably an hostname62 return False63 else: # do not check for ipv664 return True65 except OSError:66 pass67 68 return False69 