Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/net/MulticastSocket.java
38829 views
/*1* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.net;2627import java.io.IOException;28import java.util.Enumeration;2930/**31* The multicast datagram socket class is useful for sending32* and receiving IP multicast packets. A MulticastSocket is33* a (UDP) DatagramSocket, with additional capabilities for34* joining "groups" of other multicast hosts on the internet.35* <P>36* A multicast group is specified by a class D IP address37* and by a standard UDP port number. Class D IP addresses38* are in the range <CODE>224.0.0.0</CODE> to <CODE>239.255.255.255</CODE>,39* inclusive. The address 224.0.0.0 is reserved and should not be used.40* <P>41* One would join a multicast group by first creating a MulticastSocket42* with the desired port, then invoking the43* <CODE>joinGroup(InetAddress groupAddr)</CODE>44* method:45* <PRE>46* // join a Multicast group and send the group salutations47* ...48* String msg = "Hello";49* InetAddress group = InetAddress.getByName("228.5.6.7");50* MulticastSocket s = new MulticastSocket(6789);51* s.joinGroup(group);52* DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(),53* group, 6789);54* s.send(hi);55* // get their responses!56* byte[] buf = new byte[1000];57* DatagramPacket recv = new DatagramPacket(buf, buf.length);58* s.receive(recv);59* ...60* // OK, I'm done talking - leave the group...61* s.leaveGroup(group);62* </PRE>63*64* When one sends a message to a multicast group, <B>all</B> subscribing65* recipients to that host and port receive the message (within the66* time-to-live range of the packet, see below). The socket needn't67* be a member of the multicast group to send messages to it.68* <P>69* When a socket subscribes to a multicast group/port, it receives70* datagrams sent by other hosts to the group/port, as do all other71* members of the group and port. A socket relinquishes membership72* in a group by the leaveGroup(InetAddress addr) method. <B>73* Multiple MulticastSocket's</B> may subscribe to a multicast group74* and port concurrently, and they will all receive group datagrams.75* <P>76* Currently applets are not allowed to use multicast sockets.77*78* @author Pavani Diwanji79* @since JDK1.180*/81public82class MulticastSocket extends DatagramSocket {8384/**85* Used on some platforms to record if an outgoing interface86* has been set for this socket.87*/88private boolean interfaceSet;8990/**91* Create a multicast socket.92*93* <p>If there is a security manager,94* its {@code checkListen} method is first called95* with 0 as its argument to ensure the operation is allowed.96* This could result in a SecurityException.97* <p>98* When the socket is created the99* {@link DatagramSocket#setReuseAddress(boolean)} method is100* called to enable the SO_REUSEADDR socket option.101*102* @exception IOException if an I/O exception occurs103* while creating the MulticastSocket104* @exception SecurityException if a security manager exists and its105* {@code checkListen} method doesn't allow the operation.106* @see SecurityManager#checkListen107* @see java.net.DatagramSocket#setReuseAddress(boolean)108*/109public MulticastSocket() throws IOException {110this(new InetSocketAddress(0));111}112113/**114* Create a multicast socket and bind it to a specific port.115*116* <p>If there is a security manager,117* its {@code checkListen} method is first called118* with the {@code port} argument119* as its argument to ensure the operation is allowed.120* This could result in a SecurityException.121* <p>122* When the socket is created the123* {@link DatagramSocket#setReuseAddress(boolean)} method is124* called to enable the SO_REUSEADDR socket option.125*126* @param port port to use127* @exception IOException if an I/O exception occurs128* while creating the MulticastSocket129* @exception SecurityException if a security manager exists and its130* {@code checkListen} method doesn't allow the operation.131* @see SecurityManager#checkListen132* @see java.net.DatagramSocket#setReuseAddress(boolean)133*/134public MulticastSocket(int port) throws IOException {135this(new InetSocketAddress(port));136}137138/**139* Create a MulticastSocket bound to the specified socket address.140* <p>141* Or, if the address is {@code null}, create an unbound socket.142*143* <p>If there is a security manager,144* its {@code checkListen} method is first called145* with the SocketAddress port as its argument to ensure the operation is allowed.146* This could result in a SecurityException.147* <p>148* When the socket is created the149* {@link DatagramSocket#setReuseAddress(boolean)} method is150* called to enable the SO_REUSEADDR socket option.151*152* @param bindaddr Socket address to bind to, or {@code null} for153* an unbound socket.154* @exception IOException if an I/O exception occurs155* while creating the MulticastSocket156* @exception SecurityException if a security manager exists and its157* {@code checkListen} method doesn't allow the operation.158* @see SecurityManager#checkListen159* @see java.net.DatagramSocket#setReuseAddress(boolean)160*161* @since 1.4162*/163public MulticastSocket(SocketAddress bindaddr) throws IOException {164super((SocketAddress) null);165166// Enable SO_REUSEADDR before binding167setReuseAddress(true);168169if (bindaddr != null) {170try {171bind(bindaddr);172} finally {173if (!isBound())174close();175}176}177}178179/**180* The lock on the socket's TTL. This is for set/getTTL and181* send(packet,ttl).182*/183private Object ttlLock = new Object();184185/**186* The lock on the socket's interface - used by setInterface187* and getInterface188*/189private Object infLock = new Object();190191/**192* The "last" interface set by setInterface on this MulticastSocket193*/194private InetAddress infAddress = null;195196197/**198* Set the default time-to-live for multicast packets sent out199* on this {@code MulticastSocket} in order to control the200* scope of the multicasts.201*202* <p>The ttl is an <b>unsigned</b> 8-bit quantity, and so <B>must</B> be203* in the range {@code 0 <= ttl <= 0xFF }.204*205* @param ttl the time-to-live206* @exception IOException if an I/O exception occurs207* while setting the default time-to-live value208* @deprecated use the setTimeToLive method instead, which uses209* <b>int</b> instead of <b>byte</b> as the type for ttl.210* @see #getTTL()211*/212@Deprecated213public void setTTL(byte ttl) throws IOException {214if (isClosed())215throw new SocketException("Socket is closed");216getImpl().setTTL(ttl);217}218219/**220* Set the default time-to-live for multicast packets sent out221* on this {@code MulticastSocket} in order to control the222* scope of the multicasts.223*224* <P> The ttl <B>must</B> be in the range {@code 0 <= ttl <=225* 255} or an {@code IllegalArgumentException} will be thrown.226* Multicast packets sent with a TTL of {@code 0} are not transmitted227* on the network but may be delivered locally.228*229* @param ttl230* the time-to-live231*232* @throws IOException233* if an I/O exception occurs while setting the234* default time-to-live value235*236* @see #getTimeToLive()237*/238public void setTimeToLive(int ttl) throws IOException {239if (ttl < 0 || ttl > 255) {240throw new IllegalArgumentException("ttl out of range");241}242if (isClosed())243throw new SocketException("Socket is closed");244getImpl().setTimeToLive(ttl);245}246247/**248* Get the default time-to-live for multicast packets sent out on249* the socket.250*251* @exception IOException if an I/O exception occurs252* while getting the default time-to-live value253* @return the default time-to-live value254* @deprecated use the getTimeToLive method instead, which returns255* an <b>int</b> instead of a <b>byte</b>.256* @see #setTTL(byte)257*/258@Deprecated259public byte getTTL() throws IOException {260if (isClosed())261throw new SocketException("Socket is closed");262return getImpl().getTTL();263}264265/**266* Get the default time-to-live for multicast packets sent out on267* the socket.268* @exception IOException if an I/O exception occurs while269* getting the default time-to-live value270* @return the default time-to-live value271* @see #setTimeToLive(int)272*/273public int getTimeToLive() throws IOException {274if (isClosed())275throw new SocketException("Socket is closed");276return getImpl().getTimeToLive();277}278279/**280* Joins a multicast group. Its behavior may be affected by281* {@code setInterface} or {@code setNetworkInterface}.282*283* <p>If there is a security manager, this method first284* calls its {@code checkMulticast} method285* with the {@code mcastaddr} argument286* as its argument.287*288* @param mcastaddr is the multicast address to join289*290* @exception IOException if there is an error joining291* or when the address is not a multicast address.292* @exception SecurityException if a security manager exists and its293* {@code checkMulticast} method doesn't allow the join.294*295* @see SecurityManager#checkMulticast(InetAddress)296*/297public void joinGroup(InetAddress mcastaddr) throws IOException {298if (isClosed()) {299throw new SocketException("Socket is closed");300}301302checkAddress(mcastaddr, "joinGroup");303SecurityManager security = System.getSecurityManager();304if (security != null) {305security.checkMulticast(mcastaddr);306}307308if (!mcastaddr.isMulticastAddress()) {309throw new SocketException("Not a multicast address");310}311312/**313* required for some platforms where it's not possible to join314* a group without setting the interface first.315*/316NetworkInterface defaultInterface = NetworkInterface.getDefault();317318if (!interfaceSet && defaultInterface != null) {319setNetworkInterface(defaultInterface);320}321322getImpl().join(mcastaddr);323}324325/**326* Leave a multicast group. Its behavior may be affected by327* {@code setInterface} or {@code setNetworkInterface}.328*329* <p>If there is a security manager, this method first330* calls its {@code checkMulticast} method331* with the {@code mcastaddr} argument332* as its argument.333*334* @param mcastaddr is the multicast address to leave335* @exception IOException if there is an error leaving336* or when the address is not a multicast address.337* @exception SecurityException if a security manager exists and its338* {@code checkMulticast} method doesn't allow the operation.339*340* @see SecurityManager#checkMulticast(InetAddress)341*/342public void leaveGroup(InetAddress mcastaddr) throws IOException {343if (isClosed()) {344throw new SocketException("Socket is closed");345}346347checkAddress(mcastaddr, "leaveGroup");348SecurityManager security = System.getSecurityManager();349if (security != null) {350security.checkMulticast(mcastaddr);351}352353if (!mcastaddr.isMulticastAddress()) {354throw new SocketException("Not a multicast address");355}356357getImpl().leave(mcastaddr);358}359360/**361* Joins the specified multicast group at the specified interface.362*363* <p>If there is a security manager, this method first364* calls its {@code checkMulticast} method365* with the {@code mcastaddr} argument366* as its argument.367*368* @param mcastaddr is the multicast address to join369* @param netIf specifies the local interface to receive multicast370* datagram packets, or <i>null</i> to defer to the interface set by371* {@link MulticastSocket#setInterface(InetAddress)} or372* {@link MulticastSocket#setNetworkInterface(NetworkInterface)}373*374* @exception IOException if there is an error joining375* or when the address is not a multicast address.376* @exception SecurityException if a security manager exists and its377* {@code checkMulticast} method doesn't allow the join.378* @throws IllegalArgumentException if mcastaddr is null or is a379* SocketAddress subclass not supported by this socket380*381* @see SecurityManager#checkMulticast(InetAddress)382* @since 1.4383*/384public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)385throws IOException {386if (isClosed())387throw new SocketException("Socket is closed");388389if (mcastaddr == null || !(mcastaddr instanceof InetSocketAddress))390throw new IllegalArgumentException("Unsupported address type");391392if (oldImpl)393throw new UnsupportedOperationException();394395checkAddress(((InetSocketAddress)mcastaddr).getAddress(), "joinGroup");396SecurityManager security = System.getSecurityManager();397if (security != null) {398security.checkMulticast(((InetSocketAddress)mcastaddr).getAddress());399}400401if (!((InetSocketAddress)mcastaddr).getAddress().isMulticastAddress()) {402throw new SocketException("Not a multicast address");403}404405getImpl().joinGroup(mcastaddr, netIf);406}407408/**409* Leave a multicast group on a specified local interface.410*411* <p>If there is a security manager, this method first412* calls its {@code checkMulticast} method413* with the {@code mcastaddr} argument414* as its argument.415*416* @param mcastaddr is the multicast address to leave417* @param netIf specifies the local interface or <i>null</i> to defer418* to the interface set by419* {@link MulticastSocket#setInterface(InetAddress)} or420* {@link MulticastSocket#setNetworkInterface(NetworkInterface)}421* @exception IOException if there is an error leaving422* or when the address is not a multicast address.423* @exception SecurityException if a security manager exists and its424* {@code checkMulticast} method doesn't allow the operation.425* @throws IllegalArgumentException if mcastaddr is null or is a426* SocketAddress subclass not supported by this socket427*428* @see SecurityManager#checkMulticast(InetAddress)429* @since 1.4430*/431public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)432throws IOException {433if (isClosed())434throw new SocketException("Socket is closed");435436if (mcastaddr == null || !(mcastaddr instanceof InetSocketAddress))437throw new IllegalArgumentException("Unsupported address type");438439if (oldImpl)440throw new UnsupportedOperationException();441442checkAddress(((InetSocketAddress)mcastaddr).getAddress(), "leaveGroup");443SecurityManager security = System.getSecurityManager();444if (security != null) {445security.checkMulticast(((InetSocketAddress)mcastaddr).getAddress());446}447448if (!((InetSocketAddress)mcastaddr).getAddress().isMulticastAddress()) {449throw new SocketException("Not a multicast address");450}451452getImpl().leaveGroup(mcastaddr, netIf);453}454455/**456* Set the multicast network interface used by methods457* whose behavior would be affected by the value of the458* network interface. Useful for multihomed hosts.459* @param inf the InetAddress460* @exception SocketException if there is an error in461* the underlying protocol, such as a TCP error.462* @see #getInterface()463*/464public void setInterface(InetAddress inf) throws SocketException {465if (isClosed()) {466throw new SocketException("Socket is closed");467}468checkAddress(inf, "setInterface");469synchronized (infLock) {470getImpl().setOption(SocketOptions.IP_MULTICAST_IF, inf);471infAddress = inf;472interfaceSet = true;473}474}475476/**477* Retrieve the address of the network interface used for478* multicast packets.479*480* @return An {@code InetAddress} representing481* the address of the network interface used for482* multicast packets.483*484* @exception SocketException if there is an error in485* the underlying protocol, such as a TCP error.486*487* @see #setInterface(java.net.InetAddress)488*/489public InetAddress getInterface() throws SocketException {490if (isClosed()) {491throw new SocketException("Socket is closed");492}493synchronized (infLock) {494InetAddress ia =495(InetAddress)getImpl().getOption(SocketOptions.IP_MULTICAST_IF);496497/**498* No previous setInterface or interface can be499* set using setNetworkInterface500*/501if (infAddress == null) {502return ia;503}504505/**506* Same interface set with setInterface?507*/508if (ia.equals(infAddress)) {509return ia;510}511512/**513* Different InetAddress from what we set with setInterface514* so enumerate the current interface to see if the515* address set by setInterface is bound to this interface.516*/517try {518NetworkInterface ni = NetworkInterface.getByInetAddress(ia);519Enumeration<InetAddress> addrs = ni.getInetAddresses();520while (addrs.hasMoreElements()) {521InetAddress addr = addrs.nextElement();522if (addr.equals(infAddress)) {523return infAddress;524}525}526527/**528* No match so reset infAddress to indicate that the529* interface has changed via means530*/531infAddress = null;532return ia;533} catch (Exception e) {534return ia;535}536}537}538539/**540* Specify the network interface for outgoing multicast datagrams541* sent on this socket.542*543* @param netIf the interface544* @exception SocketException if there is an error in545* the underlying protocol, such as a TCP error.546* @see #getNetworkInterface()547* @since 1.4548*/549public void setNetworkInterface(NetworkInterface netIf)550throws SocketException {551552synchronized (infLock) {553getImpl().setOption(SocketOptions.IP_MULTICAST_IF2, netIf);554infAddress = null;555interfaceSet = true;556}557}558559/**560* Get the multicast network interface set.561*562* @exception SocketException if there is an error in563* the underlying protocol, such as a TCP error.564* @return the multicast {@code NetworkInterface} currently set565* @see #setNetworkInterface(NetworkInterface)566* @since 1.4567*/568public NetworkInterface getNetworkInterface() throws SocketException {569NetworkInterface ni570= (NetworkInterface)getImpl().getOption(SocketOptions.IP_MULTICAST_IF2);571if ((ni.getIndex() == 0) || (ni.getIndex() == -1)) {572InetAddress[] addrs = new InetAddress[1];573addrs[0] = InetAddress.anyLocalAddress();574return new NetworkInterface(addrs[0].getHostName(), 0, addrs);575} else {576return ni;577}578}579580/**581* Disable/Enable local loopback of multicast datagrams582* The option is used by the platform's networking code as a hint583* for setting whether multicast data will be looped back to584* the local socket.585*586* <p>Because this option is a hint, applications that want to587* verify what loopback mode is set to should call588* {@link #getLoopbackMode()}589* @param disable {@code true} to disable the LoopbackMode590* @throws SocketException if an error occurs while setting the value591* @since 1.4592* @see #getLoopbackMode593*/594public void setLoopbackMode(boolean disable) throws SocketException {595getImpl().setOption(SocketOptions.IP_MULTICAST_LOOP, Boolean.valueOf(disable));596}597598/**599* Get the setting for local loopback of multicast datagrams.600*601* @throws SocketException if an error occurs while getting the value602* @return true if the LoopbackMode has been disabled603* @since 1.4604* @see #setLoopbackMode605*/606public boolean getLoopbackMode() throws SocketException {607return ((Boolean)getImpl().getOption(SocketOptions.IP_MULTICAST_LOOP)).booleanValue();608}609610/**611* Sends a datagram packet to the destination, with a TTL (time-612* to-live) other than the default for the socket. This method613* need only be used in instances where a particular TTL is desired;614* otherwise it is preferable to set a TTL once on the socket, and615* use that default TTL for all packets. This method does <B>not616* </B> alter the default TTL for the socket. Its behavior may be617* affected by {@code setInterface}.618*619* <p>If there is a security manager, this method first performs some620* security checks. First, if {@code p.getAddress().isMulticastAddress()}621* is true, this method calls the622* security manager's {@code checkMulticast} method623* with {@code p.getAddress()} and {@code ttl} as its arguments.624* If the evaluation of that expression is false,625* this method instead calls the security manager's626* {@code checkConnect} method with arguments627* {@code p.getAddress().getHostAddress()} and628* {@code p.getPort()}. Each call to a security manager method629* could result in a SecurityException if the operation is not allowed.630*631* @param p is the packet to be sent. The packet should contain632* the destination multicast ip address and the data to be sent.633* One does not need to be the member of the group to send634* packets to a destination multicast address.635* @param ttl optional time to live for multicast packet.636* default ttl is 1.637*638* @exception IOException is raised if an error occurs i.e639* error while setting ttl.640* @exception SecurityException if a security manager exists and its641* {@code checkMulticast} or {@code checkConnect}642* method doesn't allow the send.643*644* @deprecated Use the following code or its equivalent instead:645* ......646* int ttl = mcastSocket.getTimeToLive();647* mcastSocket.setTimeToLive(newttl);648* mcastSocket.send(p);649* mcastSocket.setTimeToLive(ttl);650* ......651*652* @see DatagramSocket#send653* @see DatagramSocket#receive654* @see SecurityManager#checkMulticast(java.net.InetAddress, byte)655* @see SecurityManager#checkConnect656*/657@Deprecated658public void send(DatagramPacket p, byte ttl)659throws IOException {660if (isClosed())661throw new SocketException("Socket is closed");662checkAddress(p.getAddress(), "send");663synchronized(ttlLock) {664synchronized(p) {665if (connectState == ST_NOT_CONNECTED) {666// Security manager makes sure that the multicast address667// is allowed one and that the ttl used is less668// than the allowed maxttl.669SecurityManager security = System.getSecurityManager();670if (security != null) {671if (p.getAddress().isMulticastAddress()) {672security.checkMulticast(p.getAddress(), ttl);673} else {674security.checkConnect(p.getAddress().getHostAddress(),675p.getPort());676}677}678} else {679// we're connected680InetAddress packetAddress = null;681packetAddress = p.getAddress();682if (packetAddress == null) {683p.setAddress(connectedAddress);684p.setPort(connectedPort);685} else if ((!packetAddress.equals(connectedAddress)) ||686p.getPort() != connectedPort) {687throw new SecurityException("connected address and packet address" +688" differ");689}690}691byte dttl = getTTL();692try {693if (ttl != dttl) {694// set the ttl695getImpl().setTTL(ttl);696}697// call the datagram method to send698getImpl().send(p);699} finally {700// set it back to default701if (ttl != dttl) {702getImpl().setTTL(dttl);703}704}705} // synch p706} //synch ttl707} //method708}709710711