简体   繁体   中英

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?

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")

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM