Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if the user have entered hostname or IP address?

Tags:

python

The user will input either hostname or the IP address. If the user enters the IP address, I want to leave as it is but if the user enters the hostname I want to convert it into IP address using the following method:

def convert(hostname):
    command = subprocess.Popen(['host', hostname],
                           stdout=subprocess.PIPE).communicate()[0]

    progress1 = re.findall(r'\d+.', command)
    progress1 = ''.join(progress1)
    return progress1 

How do I do it?

like image 583
user1881957 Avatar asked Sep 21 '25 01:09

user1881957


2 Answers

To get ip whether input is ip or hostname:

ip4 = socket.gethostbyname(ip4_or_hostname)
like image 69
jfs Avatar answered Sep 22 '25 15:09

jfs


you can use a regex to match your input and test if it is a ip address or not

test = re.compile('\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
result = test.match(hostname)
if not result:
    # no match -> must be an hostname #
    convert(hostname)

that regex allows invalid ip addresses (like 999.999.999.999) so you may want to tweak it a bit, it's just a quick example

like image 40
Samuele Mattiuzzo Avatar answered Sep 22 '25 16:09

Samuele Mattiuzzo