1 /* 2 * Copyright (c) 2010, 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 */ 29 import java.net.*; 30 import java.nio.channels.DatagramChannel; 31 32 public class ChangingAddress { 33 34 // Checks that the given DatagramSocket and DatagramChannel are bound to the 35 // same local address. check(DatagramSocket ds, DatagramChannel dc)36 static void check(DatagramSocket ds, DatagramChannel dc) { 37 InetAddress expected = ds.getLocalAddress(); 38 InetAddress actual = dc.socket().getLocalAddress(); 39 // okay if one bound to 0.0.0.0 and the other to ::0 40 if ((expected.isAnyLocalAddress() != actual.isAnyLocalAddress()) && 41 !expected.equals(actual)) 42 { 43 throw new RuntimeException("Expected: " + expected + ", actual: " + actual); 44 } 45 } 46 main(String[] args)47 public static void main(String[] args) throws Exception { 48 InetAddress lh = InetAddress.getLocalHost(); 49 SocketAddress remote = new InetSocketAddress(lh, 1234); 50 51 DatagramSocket ds = null; 52 DatagramChannel dc = null; 53 try { 54 55 ds = new DatagramSocket(); 56 dc = DatagramChannel.open().bind(new InetSocketAddress(0)); 57 check(ds, dc); 58 59 ds.connect(remote); 60 dc.connect(remote); 61 check(ds, dc); 62 63 ds.disconnect(); 64 dc.disconnect(); 65 check(ds, dc); 66 67 // repeat tests using socket adapter 68 ds.connect(remote); 69 dc.socket().connect(remote); 70 check(ds, dc); 71 72 ds.disconnect(); 73 dc.socket().disconnect(); 74 check(ds, dc); 75 76 } finally { 77 if (ds != null) ds.close(); 78 if (dc != null) dc.close(); 79 } 80 } 81 } 82