[Tutor] Socket Module

Alan Gauld alan.gauld at btinternet.com
Mon Jul 20 10:59:59 CEST 2015


On 20/07/15 00:55, Nym City via Tutor wrote:
> Thank you for your response. I gave it another try:
> As suggested, first I ran the concept just in the terminal, and it worked fine:
>>>> names =['173.252.120.6', '98.139.183.24']
>>>> import socket
>>>> for name in names:
>      socket.gethostbyaddr(name)
>      print(name)
>
> output:
> ('edge-star-shv-12-frc3.facebook.com', [], ['173.252.120.6'])
> ('ir2.fp.vip.bf1.yahoo.com', [], ['98.139.183.24'])

Remember that the >>> prompt evaluates your results and
automatically prints them for you.

Thus

 >>> 5 + 3
8

But if you put code in a script and execute it the interpreter
does NOT print out arbitrary expressions so a file add.py
containing just

5 + 3

will not output anything, you need the print function:

print(5+3)

to see the result.

So in the interpreter your gethostbyaddr() function is
evaluated AND printed. But in a script it will only be
evaluated...

> import csv
> import socket
>
> domains = []
>
> with open('top500ips.csv', 'r') as f:
>      for line in f:
>          line = line.strip()
>          domains.append(line)

You are importing csv but not using it to read your file.
But I'll ignore that for now! (in fact it looks like the
csv file really only contains the IP addresses, one per
line so csv is probably redundant here.)

Also you could do all of the above in a single line with:

domains = [line.strip() for line in open('top500ips.csv')]

But none of that matters for your specific issue...

> for name in domains:
>      socket.gethostbyaddr(name)
>      print(name)

Notice here that you run the gethostbyaddr() function but
do nothing with the result. You don't store it and you
don't print it. Instead you print the initial name that
you passed in, which does not change.

You need to create a variable to store the host result
and then print that host. And since you want to store a
set of hosts you probably want to append the results to
a list of some kind (or a dictionary based on your names?)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list