Sometimes you need to look up a list of hosts to get their IP addresses. Maybe you need to create a quick list for a hosts file, as was my case. This example also includes examples for using a list in python, creating a for loop in python, and a print statement using a custom value separator.
In the documentation for python standard libraries, you will find the socket standard library. According to documentation, “This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, MacOS, and probably additional platforms.” We will import the socket standard library to enable the use of the gethostbyname function.
The code below first puts hostnames into a list. The for loop will iterate through each hostname and try to run the print line.
The print line executes the socket.gethostbyname for the current lstNames iteration, with the results becoming the first text printed. Then, the value of n is printed, which is the value of the current lstNames iteration. Finally, you see a statement, sep = ‘\t’. I have included that as a custom value separator as I want the values to be tab separated instead of separated by a single space.
Note that the try-except is barebones, essentially going down to, “If there are any problems at all, just go on to the next hostname.” You may want to add more handling in yours, such as, which hostname failed its lookup? You will also find in the documentation that there are many exceptions specifically for the socket standard library.
import socket
lstNames = ['google.com', 'facebook.com', 'yahoo.com', 'wordpress.com']
for n in lstNames:
try:
print(socket.gethostbyname(n), n, sep = '\t')
except:
continue
The results will be as follows, or something like it. The reason people use hostnames is because IPs can change but the hostname will still point where you want it to point.
216.58.192.206 google.com 157.240.221.35 facebook.com 74.6.231.21 yahoo.com 192.0.78.9 wordpress.com
That’s it! Copy and paste it into your hosts file, if you’d like. Whatever reason you needed this, good luck and hope this helped.