[python]Resolve dns if hostname is resolvable else send as is

There are times which you need to try to resolve valid hostnames, however on user’s input there could be a possibility that the input contains ip addres, firewall objects or firewall object groups that are not resolvable.

here’s a solution which could possibly return ip address if host is resolvable if not resolvable return the value as it is.

import socket

# Input the data to host, can be ip, hostname or just a name that is not resolvable
host = ""
# Initialize to nothing, if hostname is not resolvable answer will at least contain a null string.
answer = ""
try:
    answer = socket.gethostbyname(host)
except Exception as e:
    # If not resolvable, dun care.
    pass

# if answer is not null string, or host is an ip address
# gethostbyname will return the same ip address you put in.
if answer:
    print(answer)
else: # if there is no answer, or if host is a subnet or range
    print(host)
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s