1/*
2 * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 *   - Redistributions of source code must retain the above copyright
9 *     notice, this list of conditions and the following disclaimer.
10 *
11 *   - Redistributions in binary form must reproduce the above copyright
12 *     notice, this list of conditions and the following disclaimer in the
13 *     documentation and/or other materials provided with the distribution.
14 *
15 *   - Neither the name of Oracle nor the names of its
16 *     contributors may be used to endorse or promote products derived
17 *     from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32/*
33 * This source code is provided to illustrate the usage of a given feature
34 * or technique and has been deliberately simplified. Additional steps
35 * required for a production-quality application, such as security checks,
36 * input validation and proper error handling, might not be present in
37 * this sample code.
38 */
39
40
41import java.net.InetAddress;
42import java.net.NetworkInterface;
43import java.net.UnknownHostException;
44import java.net.SocketException;
45
46/**
47 * Parses and represents a multicast address.
48 */
49
50class MulticastAddress {
51    private final InetAddress group;
52    private final int port;
53    private final NetworkInterface interf;
54
55    private MulticastAddress(InetAddress group, int port, NetworkInterface interf) {
56        this.group = group;
57        this.port = port;
58        this.interf = interf;
59    }
60
61    InetAddress group() {
62        return group;
63    }
64
65    int port() {
66        return port;
67    }
68
69    /**
70     * @return  The network interface, may be {@code null}
71     */
72    NetworkInterface interf() {
73        return interf;
74    }
75
76    /**
77     * Parses a string of the form "group:port[@interface]", returning
78     * a MulticastAddress representing the address
79     */
80    static MulticastAddress parse(String s) {
81        String[] components = s.split("@");
82        if (components.length > 2)
83            throw new IllegalArgumentException("At most one '@' expected");
84
85        // get group and port
86        String target = components[0];
87        int len = components[0].length();
88        int colon = components[0].lastIndexOf(':');
89        if ((colon < 1) || (colon > (len-2)))
90            throw new IllegalArgumentException("group:port expected");
91        String groupString = target.substring(0, colon);
92        int port = -1;
93        try {
94            port = Integer.parseInt(target.substring(colon+1, len));
95        } catch (NumberFormatException x) {
96             throw new IllegalArgumentException(x);
97        }
98
99        // handle IPv6 literal address
100        if (groupString.charAt(0) == '[') {
101            len = groupString.length();
102            if (groupString.charAt(len-1) != ']')
103                throw new IllegalArgumentException("missing ']'");
104            groupString = groupString.substring(1,len-1);
105            if (groupString.length() == 0)
106                throw new IllegalArgumentException("missing IPv6 address");
107        }
108
109        // get group address
110        InetAddress group = null;
111        try {
112            group = InetAddress.getByName(groupString);
113        } catch (UnknownHostException x) {
114            throw new IllegalArgumentException(x);
115        }
116        if (!group.isMulticastAddress()) {
117            throw new IllegalArgumentException("'" + group.getHostAddress() +
118                "' is not multicast address");
119        }
120
121        // optional interface
122        NetworkInterface interf = null;
123        if (components.length == 2) {
124            try {
125                interf = NetworkInterface.getByName(components[1]);
126            } catch (SocketException x) {
127                throw new IllegalArgumentException(x);
128            }
129            if (interf == null) {
130                throw new IllegalArgumentException("'" + components[1] +
131                   "' is not valid interface");
132            }
133        }
134        return new MulticastAddress(group, port, interf);
135    }
136}
137