4

Is there a function in Python that determines if a hostname is a domain name or an IP(v4) address?

Note, the domain name may look like: alex.foo.bar.com or even (I think this is valid): 1.2.3.com.

3
  • possible duplicate of How to check if a string matches an IP adress pattern in python? Commented Jun 3, 2015 at 16:58
  • When you say "is a hostname" do you mean ... "is a valid hostname according to a strict format", or "is a hostname that exists in public DNS" or "is a string-without-spaces-and-not-an-ip-address"? Commented Jun 3, 2015 at 17:13
  • I would be interested to know if a string "is a valid hostname according to a strict format". I would like to perform this check without going to DNS. Commented Jun 3, 2015 at 17:14

2 Answers 2

2

I'd use IPy to test if the string is an IP address, and if it isn't - assume it's a domain name. E.g.:

from IPy import IP
def isIP(str):
    try:
        IP(str)
    except ValueError:
        return False
    return True
Sign up to request clarification or add additional context in comments.

2 Comments

Be aware that IPy rejects some valid IP address representations. Dotted hexadecimal and dotted octal both fail: IP('0xC0.0x00.0x02.0xEB') and IP('0300.0000.0002.0353'). These are uncommonly used, of course, so depending on OP's needs it may be OK.
I think the library has matured and a lot of bugs have been fixed. I would recommend this answer in 2022.
2

One of the visual differences between IP and domain address is when you delete dots in the IP address the result would be a number. So based on this difference we can check if the input string is an IP or a domain address. We remove dots in the input string and after that check if we can convert the result to an integer or we get an exception.

def is_ip(address):
    return address.replace('.', '').isnumeric()

Although in some IP-Representations like dotted hexadecimal (e.g. 0xC0.0x00.0x02.0xEB) there can be both letters and numbers in the IP-Address. However the top-level-domain (.org, .com, ...) never includes numbers. Using the function below will work in even more cases than the function above.

def is_ip(address):
    return not address.split('.')[-1].isalpha()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.