1 /*
   2  * Copyright (c) 2007, 2008, 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 4527345 7026376
  26  * @summary Unit test for DatagramChannel's multicast support
  27  * @build MulticastSendReceiveTests NetworkConfiguration
  28  * @run main MulticastSendReceiveTests
  29  */
  30 
  31 import java.nio.ByteBuffer;
  32 import java.nio.channels.*;
  33 import java.net.*;
  34 import static java.net.StandardProtocolFamily.*;
  35 import java.util.*;
  36 import java.io.IOException;
  37 
  38 public class MulticastSendReceiveTests {
  39 
  40     static final Random rand = new Random();
  41 
  42     static final ProtocolFamily UNSPEC = new ProtocolFamily() {
  43         public String name() {
  44             return "UNSPEC";
  45         }
  46     };
  47 
  48     /**
  49      * Send datagram from given local address to given multicast
  50      * group.
  51      */
  52     static int sendDatagram(InetAddress local,
  53                             NetworkInterface nif,
  54                             InetAddress group,
  55                             int port)
  56         throws IOException
  57     {
  58         ProtocolFamily family = (group instanceof Inet6Address) ?
  59             StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
  60         DatagramChannel dc = DatagramChannel.open(family)
  61             .bind(new InetSocketAddress(local, 0))
  62             .setOption(StandardSocketOption.IP_MULTICAST_IF, nif);
  63         int id = rand.nextInt();
  64         byte[] msg = Integer.toString(id).getBytes("UTF-8");
  65         ByteBuffer buf = ByteBuffer.wrap(msg);
  66         System.out.format("Send message from %s -> group %s (id=0x%x)\n",
  67             local.getHostAddress(), group.getHostAddress(), id);
  68         dc.send(buf, new InetSocketAddress(group, port));
  69         dc.close();
  70         return id;
  71     }
  72 
  73     /**
  74      * Wait (with timeout) for datagram.
  75      *
  76      * @param   expectedSender - expected sender address, or
  77      *                           null if no datagram expected
  78      * @param   id - expected id of datagram
  79      */
  80     static void receiveDatagram(DatagramChannel dc,
  81                                 InetAddress expectedSender,
  82                                 int id)
  83         throws IOException
  84     {
  85         Selector sel = Selector.open();
  86         dc.configureBlocking(false);
  87         dc.register(sel, SelectionKey.OP_READ);
  88         ByteBuffer buf = ByteBuffer.allocateDirect(100);
  89 
  90         try {
  91             for (;;) {
  92                 System.out.println("Waiting to receive message");
  93                 sel.select(5*1000);
  94                 SocketAddress sa = dc.receive(buf);
  95 
  96                 // no datagram received
  97                 if (sa == null) {
  98                     if (expectedSender != null) {
  99                         throw new RuntimeException("Expected message not recieved");
 100                     }
 101                     System.out.println("No message received (correct)");
 102                     return;
 103                 }
 104 
 105                 // datagram received
 106 
 107                 InetAddress sender = ((InetSocketAddress)sa).getAddress();
 108                 buf.flip();
 109                 byte[] bytes = new byte[buf.remaining()];
 110                 buf.get(bytes);
 111                 int receivedId = Integer.parseInt(new String(bytes));
 112 
 113                 System.out.format("Received message from %s (id=0x%x)\n",
 114                     sender, receivedId);
 115 
 116                 if (expectedSender == null) {
 117                     if (receivedId == id)
 118                         throw new RuntimeException("Message not expected");
 119                     System.out.println("Message ignored (has wrong id)");
 120                 } else {
 121                     if (sender.equals(expectedSender)) {
 122                         System.out.println("Message expected");
 123                         return;
 124                     }
 125                     System.out.println("Message ignored (wrong sender)");
 126                 }
 127 
 128                 sel.selectedKeys().clear();
 129                 buf.rewind();
 130             }
 131         } finally {
 132             sel.close();
 133         }
 134     }
 135 
 136 
 137     /**
 138      * Exercise multicast send/receive on given group/interface
 139      */
 140     static void test(ProtocolFamily family,
 141                      NetworkInterface nif,
 142                      InetAddress group,
 143                      InetAddress source)
 144         throws IOException
 145     {
 146         System.out.format("\nTest DatagramChannel to %s socket\n", family.name());
 147         try (DatagramChannel dc = (family == UNSPEC) ?
 148                 DatagramChannel.open() : DatagramChannel.open(family)) {
 149             dc.setOption(StandardSocketOption.SO_REUSEADDR, true)
 150               .bind(new InetSocketAddress(0));
 151 
 152             // join group
 153             System.out.format("join %s @ %s\n", group.getHostAddress(),
 154                 nif.getName());
 155             MembershipKey key;
 156             try {
 157                 key = dc.join(group, nif);
 158             } catch (IllegalArgumentException iae) {
 159                 if (family == UNSPEC) {
 160                     System.out.println("Not supported");
 161                     return;
 162                 }
 163                 throw iae;
 164             }
 165 
 166             // send message to group
 167             int port = ((InetSocketAddress)dc.getLocalAddress()).getPort();
 168             int id = sendDatagram(source, nif, group, port);
 169 
 170             // receive message and check id matches
 171             receiveDatagram(dc, source, id);
 172 
 173             // exclude-mode filtering
 174 
 175             try {
 176                 System.out.format("block %s\n", source.getHostAddress());
 177 
 178                 // may throw UOE
 179                 key.block(source);
 180                 id = sendDatagram(source, nif, group, port);
 181                 receiveDatagram(dc, null, id);
 182 
 183                 // unblock source, send message, message should be received
 184                 System.out.format("unblock %s\n", source.getHostAddress());
 185                 key.unblock(source);
 186                 id = sendDatagram(source, nif, group, port);
 187                 receiveDatagram(dc, source, id);
 188             } catch (UnsupportedOperationException x) {
 189                 System.out.println("Exclude-mode filtering not supported!");
 190             }
 191 
 192             key.drop();
 193 
 194             // include-mode filtering
 195 
 196             InetAddress bogus = (group instanceof Inet6Address) ?
 197                 InetAddress.getByName("fe80::1234") :
 198                 InetAddress.getByName("1.2.3.4");
 199             System.out.format("join %s @ %s only-source %s\n", group.getHostAddress(),
 200                 nif.getName(), bogus.getHostAddress());
 201             try {
 202                 // may throw UOE
 203                 key = dc.join(group, nif, bogus);
 204 
 205                 id = sendDatagram(source, nif, group, port);
 206                 receiveDatagram(dc, null, id);
 207 
 208                 System.out.format("join %s @ %s only-source %s\n", group.getHostAddress(),
 209                     nif.getName(), source.getHostAddress());
 210                 key = dc.join(group, nif, source);
 211 
 212                 id = sendDatagram(source, nif, group, port);
 213                 receiveDatagram(dc, source, id);
 214             } catch (UnsupportedOperationException x) {
 215                 System.out.println("Include-mode filtering not supported!");
 216             }
 217         }
 218     }
 219 
 220     public static void main(String[] args) throws IOException {
 221         NetworkConfiguration config = NetworkConfiguration.probe();
 222 
 223         // multicast groups used for the test
 224         InetAddress ip4Group = InetAddress.getByName("225.4.5.6");
 225         InetAddress ip6Group = InetAddress.getByName("ff02::a");
 226 
 227         for (NetworkInterface nif: config.ip4Interfaces()) {
 228             InetAddress source = config.ip4Addresses(nif).iterator().next();
 229             test(INET,   nif, ip4Group, source);
 230             test(UNSPEC, nif, ip4Group, source);
 231         }
 232 
 233         for (NetworkInterface nif: config.ip6Interfaces()) {
 234             InetAddress source = config.ip6Addresses(nif).iterator().next();
 235             test(INET6,  nif, ip6Group, source);
 236             test(UNSPEC, nif, ip6Group, source);
 237         }
 238     }
 239 }