1 18 package net.sf.drftpd.util; 19 20 import java.util.Random ; 21 22 import org.apache.log4j.Logger; 23 24 28 public class PortRange { 29 private static final Logger logger = Logger.getLogger(PortRange.class); 30 private int _minPort; 31 private boolean _ports[]; 32 33 Random rand = new Random (); 34 35 38 public PortRange() { 39 this(49152, 65535); 40 } 41 42 public PortRange(int minPort, int maxPort) { 43 _ports = new boolean[maxPort - minPort]; 44 _minPort = minPort; 45 } 46 47 protected void finalize() throws Throwable { 48 super.finalize(); 49 for (int i = 0; i < _ports.length; i++) { 50 if (_ports[i]) { 51 logger.debug(_minPort + i + " not released"); 52 } 53 } 54 } 55 56 59 public int getPort() { 60 synchronized (_ports) { 61 int initPos = rand.nextInt(_ports.length); 62 logger.debug("initPos: " + initPos); 63 int pos = initPos; 64 while (true) { 65 if (_ports[pos] == false) { 66 _ports[pos] = true; 67 logger.debug("returning " + _minPort + pos); 68 return _minPort + pos; 69 } else { 70 pos++; 71 if (pos == initPos) 72 throw new RuntimeException ("Portrange exhausted"); 73 if (pos > _ports.length) 74 pos = 0; 75 } 76 } 77 } 78 } 79 80 public void releasePort(int port) { 81 synchronized (_ports) { 82 if(_ports[port - _minPort] 83 != true) throw new RuntimeException ("releasePort() on unused port"); 84 _ports[port - _minPort] = false; 85 } 86 } 87 88 } 89 | Popular Tags |