python: check if IP or DNS

10,366

Solution 1

You can use re module of Python to check if the contents of the variable is a ip address.

Example for the 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 a 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

Solution 2

This will work.

import socket
host = "localhost"
if socket.gethostbyname(host) == host:
    print "It's an IP"
else:
    print "It's a host name"

Solution 3

I'd check out the answer for this SO question:

Regular expression to match DNS hostname or IP Address?

The main point is to take those two regexs and OR them together to get the desired result.

Share:
10,366
m1k3y3
Author by

m1k3y3

The Seeker, a programming enthusiast who tries to find the most optimal solutions automating daily tasks. Believe that most of them can be done through simple yet effective micro programs.

Updated on June 05, 2022

Comments

  • m1k3y3
    m1k3y3 almost 2 years

    how can one check if variable contains DNS name or IP address in python ?

  • Sandro Munda
    Sandro Munda almost 12 years
  • Ryan Chou
    Ryan Chou almost 6 years
    Awesome. both two regex would be helpful.