mchandx
mchandx

Reputation: 13

How to split the return of socket,gethostbyaddr and write to file?

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.

Upvotes: 1

Views: 4475

Answers (2)

abarnert
abarnert

Reputation: 365807

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.

Upvotes: 4

Nick ODell
Nick ODell

Reputation: 25269

What you want to do is unpack the tuple holding the information you want. There are multiple ways to do this, but this is what I would do:

(name, _, ip_address_list) = socket.gethostbyaddr(ip)
ip_address = ip_address_list[0]
destfile.write(ip_address + " resolves to " + name)

Upvotes: 4

Related Questions