I am trying to get IP address of a domain.. i am using following code
>> import socket
>> socket.gethostbyname('www.google.com')
its giving me following error..
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
socket.gethostbyname('www.google.com')
gaierror: [Errno 11001] getaddrinfo failed
what is wrong with my code...is there an开发者_开发知识库y other way to get ip address by domain name in python..??? please help...
Your code is correct. Perhaps you have a firewall in between you and these servers that is blocking the request?
import socket
domainName = input('Enter the domain name: ')
print(socket.gethostbyname(domainName))
I think you forgot to print it because it works for me.
# Python3 code to display hostname and
# IP address
# Importing socket library
import socket
# Function to display hostname and
# IP address
def get_Host_name_IP():
try:
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
print("Hostname : ",host_name)
print("IP : ",host_ip)
except:
print("Unable to get Hostname and IP")
# Driver code
get_Host_name_IP() #Function call
#This code is conributed by "Sharad_Bhardwaj".
That error also appears when the domain is not hosted anywhere (is not connected to any IP, any nameserver) or simply does not exist.
Here is full example, how you can get IP address by Domain Name.
import urllib.parse
import socket
import dns.resolver
def get_ip(target):
try:
print(socket.gethostbyname(target))
except socket.gaierror:
res = head(target, allow_redirects=True)
try:
print(r.headers['Host'])
except KeyError:
parsed_url = urllib.parse.urlparse(target)
hostname = parsed_url.hostname
try:
answers = dns.resolver.query(hostname, 'A')
for rdata in answers:
print(rdata.address)
except dns.resolver.NXDOMAIN:
print('ip not found')
get_ip('example.com')
精彩评论