[python] caution on using socket module to check for hostname

I had a problem which socket threw an exception when i was testing whether an object is a hostname or not.

if socket.gethostbyname(source) and "-" in address:
.....
.....
.....

the error is this socket.gaierror: [errno 11004] getaddrinfo failed this is because if the source is not a hostname but is an ip address the testing of socket.gethostbyname() will still be true.

A solution is to check if source is not an ip address this is the code snippet:

def is_ipv4_address(address):
    if "-" in address:
        ip_addr = address.split("-")
        #print(ip_addr[0], ip_addr[1])
        if IPAddress(ip_addr[0]) and IPAddress(ip_addr[1]):
            return True
        else:
            return False
    elif "/" in address:
        if IPNetwork(address):
            return True
        else:
            return False
    elif IPAddress(address):
        return True
    else:
        return False

if not is_ipv4_address(source) and "-" in source:
            # print(str(is_ipv4_address(source)), source)
            try:
                answers.append(socket.gethostbyname(source))
            except Exception as e:
                logging.error("Unknown element in the request, ignore...", e)
                pass
            source_address_field.append(collect_resolved_ip_addr(answers))
Advertisements
This entry was posted in Python, Scripting and tagged . Bookmark the permalink.

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s