0

I have an application that needs to implement no-DNS option. Therefore either question, whichever is convenient:

  • How can I differentiate a string IP address from a string hostname (domain)?
  • How can I disable DNS globally in Python socket module?

To asnwer what the no-DNS option mean, supposed to do: I think it makes sure that domain hostnames are not resolved at all, program just exists with an error instead.

ArekBulski
  • 4,520
  • 4
  • 39
  • 61

1 Answers1

1

You want to distinguish IP numbers from hostnames.

For ipv4, that's trivial:

import re

def is_ipv4(host):
    m = re.search(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', host)
    return m is not None

I defer David Syzdek for the more complex ipv6 case:

    m = re.search(r'(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))', host)

Or, rather than go the regex route, see if calling socket.inet_pton() (twice) will raise OSError.

J_H
  • 17,926
  • 4
  • 24
  • 44