[Tutor] Whois

Kent Johnson kent37 at tds.net
Sun Jan 15 15:04:43 CET 2006


Øyvind wrote:
> Hello.
> 
> I am trying to write a module that lets me check whois-info of ip-adresses:
> 
> import socket
> 
> class whois:
>     pass
> 
>     def ip(self, adresse):
>         self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>         self.s.connect(('whois.ripe.net', 43))
>         #self.s.connect(('whois.norid.no', 43))
>         self.s.send("%s \n\n" % adresse)
>         self.data = self.s.recv(8196)
>         self.page = ''
>         self.page = self.page + self.data
>         return self.page
> 
> If I run the module I get the following:
> 
<snip>
> This is just the first part of the whois-info.
> 
> However, if I don't write it into a function:
> 
<snip>
> Now I get everything, not only the first part as I did above. Why? And
> what should I do with the module in order to get all the info?

You need to put socket.recv() into a loop in your program. recv() 
returns whatever data is available when you call it, or it blocks until 
more data is available. When you run interactively, there is enough of a 
delay between commands that the whole reply is received. When you run as 
a program you only get the first part. Try something like this:

page = ''
while True:
   data = s.recv(8196)
   if not data:
     break  # data will be empty when the socket is closed
   page = page + data
return page

Note I have omitted the self qualifier - in the code you show, there is 
no benefit to making it a class, you might as well make ip() into a 
top-level function in your whois module. I would give it a more 
descriptive name as well...

This essay gives some reasons why you might want to use classes; none of 
them apply in this case:
http://www.pycs.net/users/0000323/stories/15.html

Kent



More information about the Tutor mailing list