Java to obtain the available UDP port number. The TCP method is similar to this one.
Method 1: If you do not mind obtaining the port number range, you can use the assumramsocket constructor to define 0 as its port number. The system will assign it an idle Port Number:
public static DatagramSocket getRandomPort() throws SocketException {DatagramSocket s = new DatagramSocket(0);return s;}
Method 2: If you want to use a specific range of port numbers, the simplest way is to traverse these ports in sequence until one is available:
public static DatagramSocket getRangePort(int[] ports) throws IOException {for (int port : ports) { try { return new DatagramSocket(port); } catch (IOException ex) { continue; // try next port } } // if the program gets here, no port in the range was found throw new IOException("no free port found");}
Test code:
import java.io.IOException;import java.net.DatagramSocket;import java.net.SocketException;public class UdpPortTest {public static void main(String[] args) throws IOException {DatagramSocket socket = getRandomPort();System.out.println("__________socket.getLocalPort():" + socket.getLocalPort());DatagramSocket socket2 = getRangePort(new int[] { 3843, 4584, 4843 });System.out.println("__________socket2.getLocalPort():" + socket2.getLocalPort());}public static DatagramSocket getRandomPort() throws SocketException {DatagramSocket s = new DatagramSocket(0);return s;}public static DatagramSocket getRangePort(int[] ports) throws IOException {for (int port : ports) { try { return new DatagramSocket(port); } catch (IOException ex) { continue; // try next port } } // if the program gets here, no port in the range was found throw new IOException("no free port found");}}
Print result:
__________ Socket. getlocalport (): 2156
__________ Socket2.getlocalport (): 3843
Original article: http://stackoverflow.com/questions/2675362/how-to-find-an-available-port.