3

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Alex Rothberg
  • 10,243
  • 13
  • 60
  • 120
  • possible duplicate of [How to check if a string matches an IP adress pattern in python?](http://stackoverflow.com/questions/3462784/how-to-check-if-a-string-matches-an-ip-adress-pattern-in-python) – mrks Jun 03 '15 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"? – TessellatingHeckler Jun 03 '15 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. – Alex Rothberg Jun 03 '15 at 17:14

2 Answers2

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()
Zciurus
  • 786
  • 4
  • 23
1

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    Be aware that IPy rejects some valid [IP address representations](https://en.wikipedia.org/wiki/IPv4#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. – Michael Geary Jun 03 '15 at 17:20
  • 1
    I think the library has matured and a lot of bugs have been fixed. I would recommend this answer in 2022. – Arka Mukherjee Nov 08 '22 at 07:48