Finding websites IP through reading lines

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Finding websites IP through reading lines



i am trying to achieve a task that a script can load a file and iterate through lines and finding domain ip from each line.



Tried doing it with this code:


import socket

with open('test.txt','r') as f:
for i in f.readlines():
i.strip('n')
i.strip('t')
i.strip('r')
print(socket.gethostbyname(i))

f.close()



But shows error



Traceback (most recent call last): File "ip.py", line 8, in
print(socket.gethostbyname(i)) socket.gaierror: [Errno -2] Name or service not known



Any help would be appreciated.



Thanks





The string you found could not be resolved as a hostname. You will have to catch the exception.
– Klaus D.
Aug 12 at 5:29





Even tried that too but result was same.
– Jaasus
Aug 12 at 5:30




3 Answers
3



The issue is that string.strip doesn't modify the string, rather, from the documentation:


string.strip



Return a copy of the string with leading and trailing characters removed.



Therefore, you can do something like the following:


import socket

with open('test.txt','r') as f:
for i in f.readlines():
i = i.strip('n')
i = i.strip('t')
i = i.strip('r')
print(socket.gethostbyname(i))

f.close()



Running that on a test.txt that looks like:


test.txt


test.com
google.com
yahoo.com



I get:


69.172.200.235
172.217.26.110
98.138.219.232



problem solved.



I wasn't saving the split result in my i variable which was not removing the new line character after each domain..
Appreciate every comments.



Thanks



Can you try below. it worked.
Issue is like you might be having other strings too apart from host name which might be throwing exception.


import socket

a = ['word2','www.google.co.in','word3']
for i in a:
try:
i.strip('n')
i.strip('t')
i.strip('r')
print(socket.gethostbyname(i))
except socket.gaierror:
print("Unable to get Hostname and IP")



Output:


Unable to get Hostname and IP
172.217.195.94
Unable to get Hostname and IP





i guess i tried remove new lines but it isn't working. My test.txt is as follows. test.com google.com yahoo.com
– Jaasus
Aug 12 at 5:43






Can you try reading file in UTF-8 encoding?
– Parshav Jain
Aug 12 at 5:57






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS