How To Resolve Dns In Python?
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 scrip
Solution 1:
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')
Solution 2:
#!/user/bin/env python"""
Resolve the DNS/IP address of a given domain
data returned is in the format:
(name, aliaslist, addresslist)
@filename resolveDNS.py
@version 1.01 (python ver 2.7.3)
@author LoanWolffe
"""import socket
defgetIP(d):
"""
This method returns the first IP address string
that responds as the given domain name
"""try:
data = socket.gethostbyname(d)
ip = repr(data)
return ip
except Exception:
# fail gracefully!returnFalse#defgetIPx(d):
"""
This method returns an array containing
one or more IP address strings that respond
as the given domain name
"""try:
data = socket.gethostbyname_ex(d)
ipx = repr(data[2])
return ipx
except Exception:
# fail gracefully!returnFalse#defgetHost(ip):
"""
This method returns the 'True Host' name for a
given IP address
"""try:
data = socket.gethostbyaddr(ip)
host = repr(data[0])
return host
except Exception:
# fail gracefullyreturnFalse#defgetAlias(d):
"""
This method returns an array containing
a list of aliases for the given domain
"""try:
data = socket.gethostbyname_ex(d)
alias = repr(data[1])
#print repr(data)return alias
except Exception:
# fail gracefullyreturnFalse## test it
x = raw_input("Domain name or IP address? > ")
a = getIP(x)
b = getIPx(x)
c = getHost(x)
d = getAlias(x)
print" IP ", a
print" IPx ", b
print" Host ", c
print" Alias ", d
Solution 3:
Just in case you need to use a specific host, you can always use sth like
def resolve(hostname: str):
return (
subprocess.check_output(["dig", "+short", "@8.8.8.8", hostname])
.strip()
.decode()
.split("\n")
)
which works similarly to
def test():
assertsorted(resolve("amazon.com")) == [
"176.32.103.205",
"205.251.242.103",
"54.239.28.85",
]
Solution 4:
Use raw_input
instead of input
.
Post a Comment for "How To Resolve Dns In Python?"