7

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

m1k3y3
  • 2,762
  • 8
  • 39
  • 68
  • possible duplicate http://stackoverflow.com/q/3462784/280730 – N 1.1 Mar 28 '11 at 15:39
  • and http://stackoverflow.com/q/319279/280730 – N 1.1 Mar 28 '11 at 15:39
  • possible duplicate of [Regular expression to match hostname or IP Address?](http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address) – Bryan Oakley Mar 28 '11 at 15:42
  • so many dupes, but no one closes it. :D – N 1.1 Mar 28 '11 at 15:44
  • @N1.1 because they aren't exact duplicates. There are answers to this question that aren't Regex. The question isn't asking about pattern matching in general either, it's asking about a specific one. – colithium Feb 28 '12 at 09:11

4 Answers4

12

This will work.

import socket
host = "localhost"
if socket.gethostbyname(host) == host:
    print "It's an IP"
else:
    print "It's a host name"
Rumple Stiltskin
  • 9,597
  • 1
  • 20
  • 25
8

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
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
2

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.

Community
  • 1
  • 1
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
0
print 'ip' if s.split('.')[-1].isdigit() else 'domain name'

This does not verify if either one is well-formed.

vartec
  • 131,205
  • 36
  • 218
  • 244