Well, the first step is to split the one-liner up into multiple lines:
host = socket.gethostbyaddr(ip)
Now, you can do whatever you want to that. If you don't know what you want to do, try printing out host
and type(host)
. You'll find that it's a tuple
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:
hostname = host[0]
Or:
hostname, _, addrlist = host
Now, you can write that to the output:
destfile.write('{} resolves to {}'.format(ip, hostname))
Another way to discover the same information would be to look at the documentation, which says:
Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary host name responding to the given ip_address, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IPv4/v6 addresses for the same interface on the same host (most likely containing only a single address).
Or to use the built-in help in the interpreter:
>>> help(socket.gethostbyaddr)
gethostbyaddr(host) -> (name, aliaslist, addresslist)
Return the true host name, a list of aliases, and a list of IP addresses,
for a host. The host argument is a string giving a host name or IP number.