1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package libcore.java.net;
18
19import java.io.IOException;
20import java.net.DatagramPacket;
21import java.net.DatagramSocket;
22import java.net.InetAddress;
23import java.net.MulticastSocket;
24import java.net.SocketTimeoutException;
25import libcore.junit.junit3.TestCaseWithRules;
26import libcore.junit.util.ResourceLeakageDetector;
27import org.junit.Rule;
28import org.junit.rules.TestRule;
29
30public final class MulticastSocketTest extends TestCaseWithRules {
31    @Rule
32    public TestRule guardRule = ResourceLeakageDetector.getRule();
33
34    private static final int SO_TIMEOUT = 1000;
35
36    public void testGroupReceiveIPv4() throws Exception {
37        testGroupReceive(InetAddress.getByName("239.1.1.1"));
38    }
39
40    public void testGroupReceiveIPv6() throws Exception {
41        testGroupReceive(InetAddress.getByName("ff05::1:1"));
42    }
43
44    private void testGroupReceive(InetAddress mcGroup) throws IOException {
45        final String message = "hello";
46
47        try (MulticastSocket mcSock = new MulticastSocket();
48             DatagramSocket ds = new DatagramSocket()) {
49            mcSock.setSoTimeout(SO_TIMEOUT);
50            final int mcPort = mcSock.getLocalPort();
51
52            DatagramPacket p = new DatagramPacket(message.getBytes(), message.length());
53            p.setAddress(mcGroup);
54            p.setPort(mcPort);
55
56            mcSock.joinGroup(mcGroup);
57            ds.send(p);
58            assertRecv(mcSock, true, message);
59
60            mcSock.leaveGroup(mcGroup);
61            ds.send(p);
62            assertRecv(mcSock, false, message);
63        }
64    }
65
66    private void assertRecv(MulticastSocket mcSock, boolean expectedSucceed, String expectedMsg)
67            throws IOException {
68        try {
69            byte[] buf = new byte[expectedMsg.length()];
70            DatagramPacket recvPacket = new DatagramPacket(buf, buf.length);
71            mcSock.receive(recvPacket);
72            if (expectedSucceed) {
73                assertTrue(new String(buf).equals(expectedMsg));
74            } else {
75                fail();
76            }
77        } catch (SocketTimeoutException e) {
78            if (expectedSucceed) {
79                fail();
80            }
81        }
82    }
83}
84