How to resolve DNS in Python?

JavaNoob picture JavaNoob · Oct 1, 2010 · Viewed 53.2k times · Source

I have a DNS script which allow users to resolve DNS names by typing website names on a Windows command prompt.

I have looked through several guides on the DNS resolve but my script can't still seem to resolve the names (www.google.com) or (google.com) to IP address.

The script outputs an error of

Traceback (most recent call last):
  File "C:\python\main_menu.py", line 37, in ?
    execfile('C:\python\showdns.py')
  File "C:\python\showdns.py", line 3, in ?
    x = input ("\nPlease enter a domain name that you wish to translate: ")
  File "<string>", line 0, in ?
NameError: name 'google' is not defined

The code:

import socket

x = input ("\nPlease enter a domain name that you wish to translate: ")

print ("\n\nThe IP Address of the Domain Name is: "+socket.gethostbyname_ex(x))

x = raw_input("\nSelect enter to proceed back to Main Menu\n")
if x == '1': 
execfile('C:\python\main_menu.py')

Please give advice on the codes. Thanks!

Answer

Patrice Neff picture Patrice Neff · Oct 1, 2010

input() is the wrong function to use here. It actually evaluates the string that the user entered.

Also gethostbyname_ex returns more than just a string. So your print statement would also have failed.

In your case this code should work:

import socket

x = raw_input ("\nPlease enter a domain name that you wish to translate: ")  

data = socket.gethostbyname_ex(x)
print ("\n\nThe IP Address of the Domain Name is: "+repr(data))  

x = raw_input("\nSelect enter to proceed back to Main Menu\n")  
if x == '1':   
    execfile('C:\python\main_menu.py')