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 any 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')
Related
I am currently trying to write my first Python3 program. In my program I am calling upon socket to get the IP and Hostname and write it to a file using a function (See code below). However, whenever I call the function it never outputs the IP or Hostname to the file IP.txt, it only writes the except message.
def get_Host_name_IP():
try:
f = open("IP.txt","w+")
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
f.write("Hostname : ", host_name)
f.write("IP : ", host_ip)
except:
f.write("Unable to get Hostname and IP")
write() takes one argument (string), so you need to format your strings properly:
def get_Host_name_IP():
try:
f = open("IP.txt","w+")
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
f.write(f"Hostname : {host_name}\n")
f.write(f"IP : {host_ip}")
except:
f.write("Unable to get Hostname and IP")
Hello i'm so confused on why i am getting this error
Code:
#!/usr/bin/python -w
import random
import socket
from random import randint
username = 'admin'
password = 'admin'
print 'Format:'
print '101.109'
range = raw_input("Range: ")
def main():
return '%s.%i.%i' % (range, rand(), rand())
def rand():
return randint (1,254)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
print 'Scanning %s:%s - %s' % (username, password, main())
port = (5900)
s.connect((main(), port))
Error code:
Format:
101.109
Range: 101.109
Scanning admin:admin - 101.109.154.9
Traceback (most recent call last):
File "C:\Users\Aries\Desktop\crap\Reflect.py", line 24, in <module>
s.connect((main(), port))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
So my friend wanted me to make a VNC IP scanner so thats what im doing and im making it try to connect to it finds actual VNC ips but when its doing that i get an error as you see at the top
EDIT: MORE INFO
I need to know how i can make it not give me an error if the connection is not up
Wrap your connect in a try/except block:
Host = main()
try:
s.connect((Host, port))
print "Port {} is open on host {}".format(port, Host)
except:
print "Connection failed" # or just pass
I am making a socket connection and when I try and connect to a different computer it returns the error:
Traceback (most recent call last):<br>
File "C:\Python34\Scripts\stuff\server.py", line 9, in <"module"><br> ##without the quotations the word would not appear because of the "<>" in html code.<br>
s.bind((HOST,PORT))<br>
OSError: [WinError 10049] The requested address is not valid in its context
Here is the code for the server/receiver:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = "192.168.1.157"
PORT = 5454
s.bind((HOST,PORT))
s.listen(1)
while True:
connection,client = s.accept()
try:
while True:
print(bytes.decode(connection.recv(999)))
except:
connection.close()
And here is the code for the client/sender:
import socket
HOST = input("Connect to: ")
PORT = 5454
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
while True:
text = str.encode(input("Send: "))
s.sendall(text)
It all works if I use 'localhost' for HOST in both server and client but the idea is that the receiver on someone's computer will connect to my PC and I have to input the IP of their PC for the sender.
Is it something I am doing wrong or something I missed? I am sorta new to this but I have looked at lots of tutorials and to me, this should work.
Any help is greatly appreciated.
I am following this example,
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
and I am getting this error despite good network:
>>> s.bind((host, port))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Applications/anaconda/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
How can I fix this?
Let's take a look at the docs:
socket.gethostname()
Return a string containing the hostname of the
machine where the Python interpreter is currently executing.
If you want to know the current machine’s IP address, you may want to
use gethostbyname(gethostname()). This operation assumes that there is
a valid address-to-host mapping for the host, and the assumption does
not always hold.
Note: gethostname() doesn’t always return the fully qualified domain
name; use getfqdn() (see above).
I guess this is what's happening: bind is trying to establish IP address for the host, but it fails. Run host = socket.gethostbyname(socket.gethostname()) and instead of a valid IP address you'll most probably see the same error as when calling bind.
You say the returned hostname is valid, but you have to make sure it's recognised by the DNS responder. Does the resolution work when doing, for example, ping {hostname} from the command line?
Possible solutions would be:
Fix your local DNS resolution.
Use host = socket.getfqdn() (in case you were not getting the fully qualified name which then couldn't be resolved properly). Even if it works I think you should try and fix the local resolution.
Use empty host (host = ''), which on bind would mean "listen on all available interfaces". (This is the first example in the docs.)
I have copied simple server/client python programs to test some socket communications.
If host is defined as 'localhost' or '', they work.
If I substitute the actual hostname in /etc/hosts, they fail with the socket.gaierror 2.
socket.gethostname() returns the correct value
as does 'hostname' on the command line.
Here is the server code that fails
#!/usr/bin/env python
"""
A simple echo server
"""
import socket
import sys
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print( " using host [%s] " % (host) )
s.bind((host,port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
print( data )
if data:
client.send(data)
client.close()
and here is the client program
#!/usr/bin/env python
"""
A simple echo client
"""
import socket
host = 'localhost'
port = 50000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
s.connect((host,port))
s.send('Hello, world')
data = s.recv(size)
s.close()
print( 'Received:', data )
This is the actual output from the server.py while using the gethostname() call.
using host [HP-linux]
Traceback (most recent call last):
File "server.py", line 18, in <module>
s.bind((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno -2] Name or service not known
Like I said, if I comment out the 'gethostname() calls, they work.
I have not been able to find any posts about gaierrors that have answers that work to solve this issue.
This running on SuSE Linux 13.1, and python2.7.
Thanks
This issue was resolved by adding an alias to the /etc/hosts file.
No rational answer as to why this would work.
Binding the server on hostname you're actualy binding it on local address, this is because normally there's a line in /etc/hosts like this 127.0.1.1 somehostname, this is to use lo iface instead of eth on the same machine for optimization reasons. If you want to accept connections from all interfaces use '0.0.0.0' instead.
I simply did these steps.
Ran command:
hostname
Say it returned me a value 'yourHostName'
Make an entry in your /etc/hosts file as follows.
127.0.0.1 yourHostName localhost
Reference for this information is : format of /etc/hosts file. Which you can see here.