Revision 24426,
1.2 KB
checked in by broder, 15 years ago
(diff) |
athinfo: Only timeout on the initial connection.
A Python socket's timeout parameter affects all operations (including,
e.g., recv()), not just establishing the connection.
Instead, set the timeout specifically for the connect() call, then set
it back to no timeout.
|
-
Property svn:executable set to
*
|
Line | |
---|
1 | #!/usr/bin/python |
---|
2 | |
---|
3 | import optparse |
---|
4 | import os |
---|
5 | import socket |
---|
6 | import sys |
---|
7 | |
---|
8 | ATHINFO_FALLBACK_PORT = 49155 |
---|
9 | |
---|
10 | def main(): |
---|
11 | parser = optparse.OptionParser( |
---|
12 | usage='%prog [options] host query' |
---|
13 | ) |
---|
14 | parser.add_option( |
---|
15 | '-t', '--timeout', |
---|
16 | type='float', |
---|
17 | dest='timeout', |
---|
18 | help='timeout after SECONDS', |
---|
19 | metavar='SECONDS', |
---|
20 | ) |
---|
21 | |
---|
22 | (options, args) = parser.parse_args() |
---|
23 | if len(args) != 2: |
---|
24 | parser.print_usage() |
---|
25 | return 1 |
---|
26 | host = args[0] |
---|
27 | query = args[1] |
---|
28 | |
---|
29 | try: |
---|
30 | port = socket.getservbyname('athinfo', 'tcp') |
---|
31 | except socket.error: |
---|
32 | port = ATHINFO_FALLBACK_PORT |
---|
33 | |
---|
34 | try: |
---|
35 | host_addr = socket.gethostbyname(host) |
---|
36 | except socket.error: |
---|
37 | print >>sys.stderr, 'athinfo: host %s not found' % host |
---|
38 | return 1 |
---|
39 | |
---|
40 | try: |
---|
41 | s = socket.socket() |
---|
42 | |
---|
43 | s.settimeout(options.timeout) |
---|
44 | s.connect((host_addr, port)) |
---|
45 | s.settimeout(None) |
---|
46 | |
---|
47 | s.sendall('%s\n' % query) |
---|
48 | sys.stdout.write(s.makefile().read()) |
---|
49 | except socket.error, e: |
---|
50 | print >>sys.stderr, 'athinfo: %s' % e.args[-1] |
---|
51 | return 1 |
---|
52 | except KeyboardInterrupt: |
---|
53 | return 1 |
---|
54 | |
---|
55 | |
---|
56 | if __name__ == '__main__': |
---|
57 | sys.exit(main()) |
---|
Note: See
TracBrowser
for help on using the repository browser.