Path: blob/master/test/jdk/java/net/Socket/GetLocalAddress.java
41149 views
/*1* Copyright (c) 1998, 2019, 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/*24* @test25* @bug 4106601 8026245 807142426* @library /test/lib27* @run main/othervm GetLocalAddress28* @run main/othervm -Djava.net.preferIPv4Stack=true GetLocalAddress29* @run main/othervm -Djava.net.preferIPv6Addresses=true GetLocalAddress30* @summary Test the java.net.socket.GetLocalAddress method31*32*/3334import java.net.*;35import jdk.test.lib.net.IPSupport;3637public class GetLocalAddress implements Runnable {38static ServerSocket ss;39static InetAddress addr;40static int port;4142public static void main(String args[]) throws Exception {43IPSupport.throwSkippedExceptionIfNonOperational();4445testBindNull();4647boolean error = true;48int linger = 65546;49int value = 0;50addr = InetAddress.getLocalHost();51ss = new ServerSocket();52ss.bind(new InetSocketAddress(addr, 0));53port = ss.getLocalPort();5455Thread t = new Thread(new GetLocalAddress());56t.start();57Socket soc = ss.accept();5859if(addr.equals(soc.getLocalAddress())) {60error = false;61}62if (error)63throw new RuntimeException("Socket.GetLocalAddress failed.");64soc.close();65}6667public void run() {68try {69Socket s = new Socket(addr, port);70} catch (Exception e) {71e.printStackTrace();72}73}7475static void testBindNull() throws Exception {76try (Socket soc = new Socket()) {77soc.bind(null);78if (!soc.isBound())79throw new RuntimeException(80"should be bound after bind(null)");81if (soc.getLocalPort() <= 0)82throw new RuntimeException(83"bind(null) failed, local port: " + soc.getLocalPort());84if (soc.getLocalAddress() == null)85throw new RuntimeException(86"bind(null) failed, local address is null");87}88}89}909192