Path: blob/master/test/jdk/java/nio/channels/TestUtil.java
41149 views
/*1* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* Test utilities24*25*/2627import java.io.*;28import java.net.*;29import java.nio.channels.*;30import java.util.Random;313233public class TestUtil {3435// Test hosts used by the channels tests - change these when36// executing in a different network.37public static final String UNRESOLVABLE_HOST = "blah-blah.blah-blah.blah";3839private TestUtil() { }4041// Repeatedly try random ports until we bind to one. You might be tempted42// to do this:43//44// ServerSocketChannel ssc = ServerSocketChannel.open();45// ssc.socket().bind(new InetSocketAddress(0));46// SocketAddress sa = ssc.socket().getLocalSocketAddress();47//48// but unfortunately it doesn't work on NT 4.0.49//50// Returns the bound port.51//52static int bind(ServerSocketChannel ssc) throws IOException {53InetAddress lh = InetAddress.getLocalHost();54Random r = new Random();55for (;;) {56int p = r.nextInt((1 << 16) - 1024) + 1024;57InetSocketAddress isa = new InetSocketAddress(lh, p);58try {59ssc.socket().bind(isa);60} catch (IOException x) {61continue;62}63return p;64}65}6667// A more convenient form of bind(ServerSocketChannel) that returns a full68// socket address.69//70static InetSocketAddress bindToRandomPort(ServerSocketChannel ssc)71throws IOException72{73int p = bind(ssc);74return new InetSocketAddress(InetAddress.getLocalHost(), p);75}7677private static String osName = System.getProperty("os.name");7879static boolean onWindows() {80return osName.startsWith("Windows");81}82}838485