I looked up on SO and found this answer
The solution provided is a good starting point. Based on the above requirements, the solution could be modified to fit the above use case.
If you use nslookup google.com
in your console in windows, you will find a similar output:
Non-authoritative answer:
Server: UnKnown
Address: 192.168.0.1
Name: facebook.com
Addresses: 2a03:2880:f12f:183:face:b00c:0:25de
31.13.79.35
Following the referenced solution, these two lines are the heart of our solution:
process = subprocess.Popen(["nslookup", url], stdout=subprocess.PIPE)
output = str(process.communicate()[0]).split('\\r\\n')
If you print the output in the console, you'll get a similar result to this:
["b'Server: UnKnown", 'Address: 192.168.0.1', '', 'Name: facebook.com', 'Addresses: 2a03:2880:f12f:183:face:b00c:0:25de', '\\t 31.13.79.35', '', "'"]
This list is enough for the above use case.
Next thing to do is to find a reliable way to always get the 6th element
which is "\\t 31.13.79.35"
To make things simpler, I used index slicing to get the 6th element
using output[5]
.
I've tested this code about 10-15 times using different urls and I've gotten similar results. A better way would be to somehow detect the address by iterating through the list items in output.
Again for the above use case, using output[5]
works well enough. If someone can contribute a more reliable way to detect the ip address in the list, please do so.
get_ip_address.py
import subprocess
def get_ip_address(url):
process = subprocess.Popen(
["nslookup", url], stdout=subprocess.PIPE)
output = str(process.communicate()[0]).split('\\r\\n')
address = output[5].replace('\\t ', '')
return address
print(get_ip_address('google.com'))