Package PyFoam :: Package Infrastructure :: Module NetworkHelpers
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.Infrastructure.NetworkHelpers

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