1 /* 2 * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /* @test 25 * @bug 6431343 26 * @summary Test that DatagramChannel.getLocalAddress returns the right local 27 * address after connect/disconnect. 28 * @run main/othervm -Djdk.net.usePlainDatagramSocketImpl=false ChangingAddress 29 */ 30 import java.net.*; 31 import java.nio.channels.DatagramChannel; 32 33 public class ChangingAddress { 34 35 // Checks that the given DatagramSocket and DatagramChannel are bound to the 36 // same local address. check(DatagramSocket ds, DatagramChannel dc)37 static void check(DatagramSocket ds, DatagramChannel dc) { 38 InetAddress expected = ds.getLocalAddress(); 39 InetAddress actual = dc.socket().getLocalAddress(); 40 // okay if one bound to 0.0.0.0 and the other to ::0 41 if ((expected.isAnyLocalAddress() != actual.isAnyLocalAddress()) && 42 !expected.equals(actual)) 43 { 44 throw new RuntimeException("Expected: " + expected + ", actual: " + actual); 45 } 46 } 47 main(String[] args)48 public static void main(String[] args) throws Exception { 49 InetAddress lh = InetAddress.getLocalHost(); 50 SocketAddress remote = new InetSocketAddress(lh, 1234); 51 52 DatagramSocket ds = null; 53 DatagramChannel dc = null; 54 try { 55 56 ds = new DatagramSocket(); 57 dc = DatagramChannel.open().bind(new InetSocketAddress(0)); 58 check(ds, dc); 59 60 ds.connect(remote); 61 dc.connect(remote); 62 check(ds, dc); 63 64 ds.disconnect(); 65 dc.disconnect(); 66 check(ds, dc); 67 68 // repeat tests using socket adapter 69 ds.connect(remote); 70 dc.socket().connect(remote); 71 check(ds, dc); 72 73 ds.disconnect(); 74 dc.socket().disconnect(); 75 check(ds, dc); 76 77 } finally { 78 if (ds != null) ds.close(); 79 if (dc != null) dc.close(); 80 } 81 } 82 } 83