How do you specify a port range for Java sockets?

后端 未结 4 1488
死守一世寂寞
死守一世寂寞 2021-01-17 15:55

In Java you can give the number zero as a single parameter for the Socket or DatagramSocket constructor. Java binds that Socket to a free port then. Is it possible to limit

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 16:31

    Here's the code you need:

    public static Socket getListeningSocket() {
        for ( int port = MIN_PORT ; port <= MAX_PORT ; port++ )
        {
            try {
                ServerSocket s = new ServerSocket( port );
                return s;      // no exception means port was available
            } catch (IOException e) {
                // try the next port
            }
        }
        return null;   // port not found, perhaps throw exception?
    }
    

提交回复
热议问题