FileDocCategorySizeDatePackage
Support_PortManager.javaAPI DocAndroid 1.5 API3317Wed May 06 22:41:06 BST 2009tests.support

Support_PortManager

public class Support_PortManager extends Object
The port manager is supposed to help finding a free network port on the machine; however, it uses strange logic, so leave it to the OS.
deprecated
Use OS to find free ports.

Fields Summary
private static int
lastAssignedPort
private static boolean
failedOnce
Constructors Summary
Methods Summary
public static synchronized intgetNextPort()


         
        if (!failedOnce) {
            try {
                ServerSocket ss = new ServerSocket(0);
                int port = ss.getLocalPort();

                ss.close();
                return port;
            } catch (Exception ex) {
                failedOnce = true;
            }
        }
        return getNextPort_unsafe();
    
public static synchronized intgetNextPortForUDP()
Returns 1 free ports to be used.

        return getNextPortsForUDP(1)[0];
    
public static synchronized intgetNextPort_unsafe()

        if (++lastAssignedPort > 65534) {
            lastAssignedPort = 6000;
        }
        return lastAssignedPort;
    
public static synchronized int[]getNextPortsForUDP(int num)
Returns the specified number of free ports to be used.

        if (num <= 0) {
            throw new IllegalArgumentException("Invalid ports number: " + num);
        }
        DatagramSocket[] dss = new DatagramSocket[num];
        int[] ports = new int[num];

        try {
            for (int i = 0; i < num; ++i) {
                dss[i] = new DatagramSocket(0);
                ports[i] = dss[i].getLocalPort();
            }
        } catch (Exception ex) {
            throw new Error("Unable to get " + num + " ports for UDP: " + ex);
        } finally {
            for (int i = 0; i < num; ++i) {
                if (dss[i] != null) {
                    dss[i].close();
                }
            }
        }
        return ports;
    
private static intsomewhatRandomPort()

        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        int minutes = c.get(Calendar.MINUTE);
        int seconds = c.get(Calendar.SECOND);

        return 6000 + (1000 * minutes) + ((seconds / 6) * 100);