2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 package tests.support;
20 import java.net.DatagramSocket;
21 import java.net.ServerSocket;
22 import java.util.Calendar;
23 import java.util.TimeZone;
26 * The port manager is supposed to help finding a free
27 * network port on the machine; however, it uses strange
28 * logic, so leave it to the OS.
30 * @deprecated Use OS to find free ports.
32 public class Support_PortManager {
34 private static int lastAssignedPort = somewhatRandomPort();
35 private static boolean failedOnce = false;
37 public static synchronized int getNextPort() {
40 ServerSocket ss = new ServerSocket(0);
41 int port = ss.getLocalPort();
45 } catch (Exception ex) {
49 return getNextPort_unsafe();
53 * Returns 1 free ports to be used.
55 public static synchronized int getNextPortForUDP() {
56 return getNextPortsForUDP(1)[0];
60 * Returns the specified number of free ports to be used.
62 public static synchronized int[] getNextPortsForUDP(int num) {
64 throw new IllegalArgumentException("Invalid ports number: " + num);
66 DatagramSocket[] dss = new DatagramSocket[num];
67 int[] ports = new int[num];
70 for (int i = 0; i < num; ++i) {
71 dss[i] = new DatagramSocket(0);
72 ports[i] = dss[i].getLocalPort();
74 } catch (Exception ex) {
75 throw new Error("Unable to get " + num + " ports for UDP: " + ex);
77 for (int i = 0; i < num; ++i) {
86 public static synchronized int getNextPort_unsafe() {
87 if (++lastAssignedPort > 65534) {
88 lastAssignedPort = 6000;
90 return lastAssignedPort;
94 * Returns a different port number every 6 seconds or so. The port number
95 * should be about += 100 at each 6 second interval
97 private static int somewhatRandomPort() {
98 Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
99 int minutes = c.get(Calendar.MINUTE);
100 int seconds = c.get(Calendar.SECOND);
102 return 6000 + (1000 * minutes) + ((seconds / 6) * 100);