I'm trying to get the ip address of a website given from args. When I try with the website directly in the source code like 'url='https://google.com' it works but when I try with 'url = sys.argv[1]' it fails.
When I print the 'url = sys.argv[1]' I get the desired website. I tried to str(url) it but it doesn't work neither.
Here's the code :
import socket
import sys
# Params
url = sys.argv[1]
# url = str(sys.argv[1])
print (type(url)) # I get the desired url
s = socket.socket()
# Get IP
ip = socket.gethostbyname(url)
# Print Infos
print ('IP Adress : ' + ip + '\n' + 15*'-')
s.close()
Do you have any idea?
Thank you, it's driving me crazy.
It is because you're passing in the https//:
; you need to remove it:
In [3]: ip = socket.gethostbyname("http://google.com")
---------------------------------------------------------------------------
gaierror Traceback (most recent call last)
<ipython-input-3-7466d856e904> in <module>()
----> 1 ip = socket.gethostbyname("http://google.com")
Instead, try:
In [4]: ip = socket.gethostbyname("google.com")
In [5]: ip
Out[5]: '172.217.25.238'
Note that you'll also want to remove any trailing slashes, for example, remove /
in google.com/
.
If you look at man gethostbyname
you'll see that you're making a DNS request:
The
gethostbyname()
function returns a structure of type hostent for the given host name. Here name is either a hostname or an IPv4 address in standard dot notation (as forinet_addr(3)
).
So, you need to make sure you cleanup anything you pass to that function call.