[Python Patterns] See if your hostname is really an IP address

I liked this one due to the simple regex. It is rather dumb out of context though.

I liked this one due to the simple regex.  It is rather dumb out of context though.

import re

def hostname_is_ip(hostname):
    regex = '(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
    match = re.search(regex, hostname)
    if match:
        print("You entered an IP address")
        return "ip"
    else:
        print("You entered a hostname")
        return "ok"

Output:

>>> hostname_is_ip('bob')
You entered a hostname
'ok'
>>> hostname_is_ip('10.1.1.1')
You entered an IP address
'ip'
>>> 

My blog posts tagged with "Python Patterns" are designed to be a quick look reference for some Python code snippets I use a lot.  They are written to be a quick starting point for future projects so I do not need to type as much.