Thanos Infosec
Thanos Infosec

Reputation: 57

Distinguish between an IP address and FQDN

Do you know if there is any pattern/logic that could be used to distinguish between an IP address and an FQDN in python? I have a script that process user input which could be ip or fqdn and i would like to to ip validation checks if ip, and no validation check in case it is fqdn.

addy = "1.2.3.4"
a = addy.split('.')
match = re.search('^(([0-9]|[0-9][0-9]|[0-9][0-9][0-9]))$', a[0])
if match is not None:
   if is_valid_ipv4(addy) == True:
      # code continues

what is case addy is fqdn? I wish to call is_valid_ipv4 if input string is only an IP address. Do I need a pattern for FQDN? How to distinguish between IP and FQDN?

Upvotes: 0

Views: 1015

Answers (2)

Amadan
Amadan

Reputation: 198334

Python knows about IP addresses. Meanwhile, this answer gives a pretty good regexp for validating FQDNs.

import ipaddress
import re

addy = "192.0.2.1"

fqdn_re = re.compile('(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}\.?$)')

try:
    ip_addy = ipaddress.ip_address(addy)
    if ip_addy.version == 4:
        print("IPv4 address")
    elif ip_addy.version == 6:
        print("IPv6 address")
except ValueError:
    if fqdn_re.search(addy):
        print("FQDN address")
    else:
        print("Invalid address")

Upvotes: 4

s3dev
s3dev

Reputation: 9701

Personally, I'd use regex. In Python you can use the re package.

Write a pattern for each (IP and FQDN) and see which gets a match (re.match()).

Here are some useful links:

Upvotes: -1

Related Questions