Keeping a function from taking to long--threads?

G

Guest

Hi All,
Just wondering if anyone knows of a way to keep a function,
E.g. socket.gethostbyaddr("12.34.56.78"),
From taking to long-if it's run for more than 1 second, the function
gethostbyaddr will be terminated?
I was thinking about using threads, but I can't seem to get the hang of
them.
I've tried to have the script break if the clock time is greater than 1
second, but python won't respond to anything until the function finishes,
not surprisingly.
Sorry if there is a very obvious answer to this...
The below program is to do a search on our wireless network at work, so that
we can find any rogue computers that aren't supposed to be there.

Code:

#code starts
import socket
import sys
changingip=[]
ip=sys.argv[1]
ip=ip.split(".")
for i in range(0,254):
ipaddr=ip[0]+"."+ip[1]+"."+ip[2]+"."+str(i)
try:
#the next line is my issue; I need to make sure it doesn't go over 1 second
while running
print socket.gethostbyaddr(ipaddr)
#the next block is to ensure that if the ip I am checking doesn't exist on
the network, the script will move along to the next ip
except:
pass

#end of script
#I know the code isn't pretty, but except for the timeing issues, it works
great.

Any help is greatly appreciated.
THX,
Brandon McGinty
 
R

Rene Pijlman

Just wondering if anyone knows of a way to keep a function,
E.g. socket.gethostbyaddr("12.34.56.78"),
gethostbyaddr will be terminated?

import socket
socket.setdefaulttimeout(1)
 
S

Steve Holden

Thanks, however, I forgot to mention that I'm using windows, and from what
I've tried, the setdefaulttimeout function doesn't work on my machine.
Again, thanks for your help!
Brandon McGinty
What version of Python are you running? Under 3.4 setdefaulttimeout()
works perfectly well on my Windows system.

If you are running 2.3 or earlier, you may want to use Timothy
O'Malley's timeoutsocket module instead.

However, you seem to be assuming that socket.gethostbyaddr() will report
>>> import socket
>>> socket.gethostbyaddr("127.0.0.1") ('localhost', [], ['127.0.0.1'])
>>> socket.gethostbyaddr("192.168.10.215") ('bigboy.lan', [], ['192.168.10.215'])
>>> socket.gethostbyaddr("82.165.194.52") ('perfora.net', [], ['82.165.194.52'])
>>>

So it will tell you something about the DNS service's content rather
than the existence or non-existence of systems at a particular IP address.

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,123
Latest member
Layne6498
Top