2

I need to get ip address of website, for example, 'https://www.facebook.com/'

This code returns ip address:

ip_address = socket.gethostbyname('www.facebook.com')
print('ip_address = ', ip_address) # prints 185.60.216.35

But this code:

  ip_address = socket.gethostbyname('https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110')

throws an exception:

socket.gaierror: [Errno -2] Name or service not known

Is there any way in python to get ip address from this link 'https://www.facebook.com/' without retrieving www.facebook.com ?

asd23
  • 23
  • 2
  • 1
    Possible duplicate of [Get protocol + host name from URL](https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url) – nishant Jan 13 '19 at 17:21

1 Answers1

3

You can use urllib.parse.urlsplit to get the hostname from the domain, then get the IP address.

urlsplit returns a namedtuple, its netloc attribute is the hostname.

>>> import socket
>>> from urllib import parse
>>> url = 'https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110'
>>> split_url = parse.urlsplit(url)
>>> ip_address = socket.gethostbyname(split_url.netloc)

>>> print(ip_address)
157.240.1.35
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153