1 18 package net.sf.drftpd.slave; 19 20 import java.io.IOException ; 21 import java.net.ServerSocket ; 22 import java.net.Socket ; 23 import java.rmi.server.RMISocketFactory ; 24 import java.util.Random ; 25 26 import org.apache.log4j.Logger; 27 28 33 public class PortRangeServerSocketFactory extends RMISocketFactory { 34 private static final Logger logger = 35 Logger.getLogger(PortRangeServerSocketFactory.class); 36 37 int _portfrom; 38 int _portto; 39 40 public PortRangeServerSocketFactory(int portfrom, int portto) { 41 if(portfrom > portfrom) throw new IllegalArgumentException ("from cannot be higher than to"); 42 _portfrom = portfrom; 43 _portto = portto; 44 } 45 46 47 public ServerSocket createServerSocket(int port) throws IOException { 48 if(port != 0) logger.error("Returning anonymous port to non-anonymous request", new Throwable ()); 49 int randport = new Random ().nextInt(_portto - _portfrom) + _portfrom; 54 int myport = randport; 55 while (true) { 56 if (myport > _portto) 58 myport = _portfrom; 59 try { 60 return new ServerSocket (myport, 1); 61 } catch (IOException e) { 62 logger.warn("Failed to listen, will try next port", e); 63 myport += 1; 64 if (myport == randport) 66 throw (IOException ) new IOException ( 67 "No available ports to listen on").initCause( 68 e); 69 } 70 } 71 } 72 73 76 public Socket createSocket(String host, int port) throws IOException { 77 return new Socket (host, port); 78 } 79 82 public boolean equals(Object obj) { 83 if(obj instanceof PortRangeServerSocketFactory) { 84 PortRangeServerSocketFactory factory = (PortRangeServerSocketFactory)obj; 85 return (factory._portfrom == _portfrom && factory._portto == _portto); 86 } 87 return false; 88 } 89 90 } 91 | Popular Tags |