I have a script that reads addresses from a file and looks up its hostname with socket.gethostbyaddr, however the return of this function is messy and doesn't look right.
The line where it writes to the destination file reads:
destfile.write(str(socket.gethostbyaddr(ip)))
The results come out like this when it reads 8.8.8.8:
('google-public-dns-a.google.com', [], ['8.8.8.8])
However, I only need that first output, google-public-dns-a.google.com. I hope to have it write to the file and look like this:
8.8.8.8 resolves to google-public-dns-a.google.com
Anyone know how to split this? Can provide more code if needed.
Well, the first step is to split the one-liner up into multiple lines:
Now, you can do whatever you want to that. If you don't know what you want to do, try printing out
host
andtype(host)
. You'll find that it's atuple
of 3 elements (although in this case, you could have guessed that from the string written to the file), and you want the first. So:Or:
Now, you can write that to the output:
Another way to discover the same information would be to look at the documentation, which says:
Or to use the built-in help in the interpreter: