Python: check that IP or DNS

how to check if a variable contains a DNS name or IP address in python?

+4
source share
4 answers

You can use the re Python module to check if the contents of a variable are an IP address.

Example for ip address:

import re my_ip = "192.168.1.1" is_valid = re.match("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", my_ip) if is_valid: print "%s is a valid ip address" % my_ip 

Example for hostname:

 import re my_hostname = "testhostname" is_valid = re.match("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$", my_hostname) if is_valid: print "%s is a valid hostname" % my_hostname 
+6
source

This will work.

 import socket host = "localhost" if socket.gethostbyname(host) == host: print "It an IP" else: print "It a host name" 
+9
source

I would look at the answer to this SO question:

Regular expression to match DNS hostname or IP address?

The main thing is to take these two regular expressions and them together to get the desired result.

+1
source
 print 'ip' if s.split('.')[-1].isdigit() else 'domain name' 

This does not check if it is correctly formed.

0
source

Source: https://habr.com/ru/post/1345570/


All Articles