1 """Helpers for the networking functionality"""
2
3 import socket
4 import errno
5 import time
6
7 from PyFoam import configuration as config
8
9 import xmlrpclib,xml
10
12 """
13 Finds a port that is free for serving
14 @param start: the port to start with
15 @param length: the number of ports to scan
16 @return: number of the first free port, -1 if none is found
17 """
18 port=-1
19
20 for p in range(start,start+length):
21 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
22 try:
23 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
24 sock.bind(('',p))
25 except socket.error,e:
26 if e[0]!=errno.EADDRINUSE:
27
28 sock.close()
29 raise
30 else:
31
32 sock.close()
33 time.sleep(config().getfloat("Network","portWait"))
34 port=p
35 break
36
37
38 return port
39
41 """
42 Finds the port on a remote host on which Foam-Servers are running
43 @param host: the IP of the host that should be checked
44 @param start: the port to start with
45 @param length: the number of ports to scan
46 @return: a list with the found ports, None if the machine is unreachable
47 """
48
49 ports=[]
50
51
52
53
54
55
56
57 for p in range(start,start+length):
58 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
59 socket.setdefaulttimeout(config().getfloat("Network","socketTimeout"))
60 ok=False
61 try:
62 sock.connect((host,p))
63 sock.close()
64 except socket.error, reason:
65 code=reason[0]
66 if code==errno.EHOSTUNREACH or code==errno.ENETUNREACH or code=="timed out" or code<0:
67
68 return None
69 elif code==errno.ECONNREFUSED:
70
71 continue
72 else:
73 print errno.errorcode[code]
74 raise reason
75
76 try:
77 server=xmlrpclib.ServerProxy("http://%s:%d" % (host,p))
78 ok=server.isFoamServer()
79 except xmlrpclib.ProtocolError, reason:
80 pass
81 except xml.parsers.expat.ExpatError, reason:
82 pass
83
84 if ok:
85 ports.append(p)
86
87 return ports
88