home *** CD-ROM | disk | FTP | other *** search
/ Apple Developer Connection Student Program / ADC Tools Sampler CD Disk 3 1999.iso / Metrowerks CodeWarrior / Java Support / Java_Source / Java2 / src / java / net / MulticastSocket.java < prev    next >
Encoding:
Java Source  |  1999-05-28  |  12.9 KB  |  356 lines  |  [TEXT/CWIE]

  1. /*
  2.  * @(#)MulticastSocket.java    1.28 98/10/14
  3.  *
  4.  * Copyright 1995-1998 by Sun Microsystems, Inc.,
  5.  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
  6.  * All rights reserved.
  7.  *
  8.  * This software is the confidential and proprietary information
  9.  * of Sun Microsystems, Inc. ("Confidential Information").  You
  10.  * shall not disclose such Confidential Information and shall use
  11.  * it only in accordance with the terms of the license agreement
  12.  * you entered into with Sun.
  13.  */
  14.  
  15. package java.net;
  16.  
  17. import java.io.IOException;
  18. import java.io.InterruptedIOException;
  19.  
  20. /**
  21.  * The multicast datagram socket class is useful for sending
  22.  * and receiving IP multicast packets.  A MulticastSocket is
  23.  * a (UDP) DatagramSocket, with additional capabilities for
  24.  * joining "groups" of other multicast hosts on the internet.
  25.  * <P>
  26.  * A multicast group is specified by a class D IP address, those
  27.  * in the range <CODE>224.0.0.1</CODE> to <CODE>239.255.255.255</CODE>,
  28.  * inclusive, and by a standard UDP port number.  One would join a
  29.  * multicast group by first creating a MulticastSocket with the desired
  30.  * port, then invoking the <CODE>joinGroup(InetAddress groupAddr)</CODE>
  31.  * method:
  32.  * <PRE>
  33.  * // join a Multicast group and send the group salutations
  34.  * ...
  35.  * byte[] msg = {'H', 'e', 'l', 'l', 'o'};
  36.  * InetAddress group = InetAddress.getByName("228.5.6.7");
  37.  * MulticastSocket s = new MulticastSocket(6789);
  38.  * s.joinGroup(group);
  39.  * DatagramPacket hi = new DatagramPacket(msg, msg.length,
  40.  *                             group, 6789);
  41.  * s.send(hi);
  42.  * // get their responses!
  43.  * byte[] buf = new byte[1000];
  44.  * DatagramPacket recv = new DatagramPacket(buf, buf.length);
  45.  * s.receive(recv);
  46.  * ...
  47.  * // OK, I'm done talking - leave the group...
  48.  * s.leaveGroup(group);
  49.  * </PRE>
  50.  *
  51.  * When one sends a message to a multicast group, <B>all</B> subscribing
  52.  * recipients to that host and port receive the message (within the
  53.  * time-to-live range of the packet, see below).  The socket needn't
  54.  * be a member of the multicast group to send messages to it.
  55.  * <P>
  56.  * When a socket subscribes to a multicast group/port, it receives
  57.  * datagrams sent by other hosts to the group/port, as do all other
  58.  * members of the group and port.  A socket relinquishes membership
  59.  * in a group by the leaveGroup(InetAddress addr) method.  <B>
  60.  * Multiple MulticastSocket's</B> may subscribe to a multicast group
  61.  * and port concurrently, and they will all receive group datagrams.
  62.  * <P>
  63.  * Currently applets are not allowed to use multicast sockets.
  64.  *
  65.  * @author Pavani Diwanji
  66.  * @since  JDK1.1
  67.  */
  68. public
  69. class MulticastSocket extends DatagramSocket {
  70.     /**
  71.      * Create a multicast socket.
  72.      * 
  73.      * <p>If there is a security manager, 
  74.      * its <code>checkListen</code> method is first called
  75.      * with 0 as its argument to ensure the operation is allowed. 
  76.      * This could result in a SecurityException.
  77.      * 
  78.      * @exception  SecurityException  if a security manager exists and its  
  79.      *             <code>checkListen</code> method doesn't allow the operation.
  80.      * @see SecurityManager#checkListen
  81.      */
  82.     public MulticastSocket() throws IOException {
  83.     super();
  84.     }
  85.  
  86.     /**
  87.      * Create a multicast socket and bind it to a specific port.
  88.      * 
  89.      * <p>If there is a security manager, 
  90.      * its <code>checkListen</code> method is first called
  91.      * with the <code>port</code> argument
  92.      * as its argument to ensure the operation is allowed. 
  93.      * This could result in a SecurityException.
  94.      * 
  95.      * @param port port to use
  96.      * @exception  SecurityException  if a security manager exists and its  
  97.      *             <code>checkListen</code> method doesn't allow the operation.
  98.      * @see SecurityManager#checkListen
  99.      */
  100.     public MulticastSocket(int port) throws IOException {
  101.     super(port);
  102.     }
  103.  
  104.     /* do the work of creating a vanilla multicast socket.  It is
  105.      * important that the signature of this method not change,
  106.      * even though it is package-private, since it is overrides a
  107.      * method from DatagramSocket, which must not set SO_REUSEADDR.
  108.      */
  109.     void create(int port, InetAddress ignore) throws SocketException {
  110.     SecurityManager security = System.getSecurityManager();
  111.     if (security != null) {
  112.         security.checkListen(port);
  113.     }
  114.     try {
  115.         this.impl = (DatagramSocketImpl) implClass.newInstance();
  116.     } catch (Exception e) {
  117.         throw new SocketException("can't instantiate DatagramSocketImpl" + e.toString());
  118.     }
  119.     impl.create();
  120.     impl.setOption(SocketOptions.SO_REUSEADDR, new Integer(-1));
  121.     impl.bind(port, InetAddress.anyLocalAddress);
  122.     }
  123.  
  124.     /**
  125.      * The lock on the socket's TTL. This is for set/getTTL and
  126.      * send(packet,ttl).
  127.      */
  128.     private Object ttlLock = new Object();
  129.  
  130.     /**
  131.      * Set the default time-to-live for multicast packets sent out
  132.      * on this socket.  The TTL sets the IP time-to-live for
  133.      * <code>DatagramPackets</code> sent to a MulticastGroup, which
  134.      * specifies how many "hops" that the packet will be forwarded
  135.      * on the network before it expires.
  136.      *
  137.      * <p>This method may only be used to set time-to-live value
  138.      * between 1 and 127. The behavior if the value is outside that
  139.      * range is undefined.
  140.      *
  141.      * @param ttl the time-to-live
  142.      *
  143.      * @deprecated use the setTimeToLive method instead, which allows
  144.      * you to set time-to-live values from 0 (excluded) to 255
  145.      * (included).
  146.      */
  147.     public void setTTL(byte ttl) throws IOException {
  148.     int ittl = -1;
  149.     if (ttl < 0) {
  150.         ittl = ttl & 0xff;
  151.     } else {
  152.         ittl = (int)ttl;
  153.     }
  154.     setTimeToLive(ittl);
  155.     }
  156.  
  157.     /**
  158.      * Set the default time-to-live for multicast packets sent out
  159.      * on this socket.  The TTL sets the IP time-to-live for
  160.      * <code>DatagramPackets</code> sent to a MulticastGroup, which
  161.      * specifies how many "hops" that the packet will be forwarded
  162.      * on the network before it expires.
  163.      *
  164.      * <P>The ttl is <B>must</B> be in the range <code> 0 < ttl <=
  165.      * 255</code> or an IllegalArgumentException will be thrown.
  166.      *
  167.      * @param ttl the time-to-live
  168.      */
  169.     public void setTimeToLive(int ttl) throws IOException {
  170.     if (ttl < 1 || ttl > 255) {
  171.         throw new IllegalArgumentException("ttl out of range");
  172.     }
  173.     impl.setTimeToLive(ttl);
  174.     }
  175.  
  176.     /**
  177.      * Get the default time-to-live for multicast packets sent out on
  178.      * the socket. This method will truncate any time to live values
  179.      * greater than 127 to 127.
  180.      *
  181.      * @deprecated use the getTimeToLive method instead, which allows
  182.      * you to get time-to-live values from 0 (excluded) to 255
  183.      * (included).
  184.      */
  185.     public byte getTTL() throws IOException {
  186.     int ttl = getTimeToLive();
  187.     if (ttl > 127) {
  188.         return (byte)127;
  189.     } else {
  190.         return (byte)ttl;
  191.     }
  192.     }
  193.  
  194.     /**
  195.      * Get the default time-to-live for multicast packets sent out on
  196.      * the socket.
  197.      */
  198.     public int getTimeToLive() throws IOException {
  199.     return impl.getTimeToLive();
  200.     }
  201.  
  202.     /**
  203.      * Joins a multicast group.
  204.      * 
  205.      * <p>If there is a security manager, this method first
  206.      * calls its <code>checkMulticast</code> method
  207.      * with the <code>mcastaddr</code> argument
  208.      * as its argument.
  209.      * 
  210.      * @param mcastaddr is the multicast address to join
  211.      * 
  212.      * @exception IOException if there is an error joining
  213.      * or when the address is not a multicast address.
  214.      * @exception  SecurityException  if a security manager exists and its  
  215.      * <code>checkMulticast</code> method doesn't allow the join.
  216.      * 
  217.      * @see SecurityManager#checkMulticast(InetAddress)
  218.      */
  219.     public void joinGroup(InetAddress mcastaddr) throws IOException {
  220.  
  221.     SecurityManager security = System.getSecurityManager();
  222.     if (security != null) {
  223.         security.checkMulticast(mcastaddr);
  224.     }
  225.     impl.join(mcastaddr);
  226.     }
  227.  
  228.     /**
  229.      * Leave a multicast group.
  230.      * 
  231.      * <p>If there is a security manager, this method first
  232.      * calls its <code>checkMulticast</code> method
  233.      * with the <code>mcastaddr</code> argument
  234.      * as its argument.
  235.      * 
  236.      * @param mcastaddr is the multicast address to leave
  237.      * @exception IOException if there is an error leaving
  238.      * or when the address is not a multicast address.
  239.      * @exception  SecurityException  if a security manager exists and its  
  240.      * <code>checkMulticast</code> method doesn't allow the operation.
  241.      * 
  242.      * @see SecurityManager#checkMulticast(InetAddress)
  243.      */
  244.     public void leaveGroup(InetAddress mcastaddr) throws IOException {
  245.  
  246.     SecurityManager security = System.getSecurityManager();
  247.     if (security != null) {
  248.         security.checkMulticast(mcastaddr);
  249.     }
  250.     impl.leave(mcastaddr);
  251.     }
  252.  
  253.     /**
  254.      * Set the outgoing network interface for multicast packets on this
  255.      * socket, to other than the system default.  Useful for multihomed
  256.      * hosts.
  257.      */
  258.     public void setInterface(InetAddress inf) throws SocketException {
  259.     impl.setOption(SocketOptions.IP_MULTICAST_IF, inf);
  260.     }
  261.  
  262.     /**
  263.      * Retrieve the address of the network interface used for
  264.      * multicast packets.
  265.      */
  266.     public InetAddress getInterface() throws SocketException {
  267.     return (InetAddress) impl.getOption(SocketOptions.IP_MULTICAST_IF);
  268.     }
  269.  
  270.     /**
  271.      * Sends a datagram packet to the destination, with a TTL (time-
  272.      * to-live) other than the default for the socket.  This method
  273.      * need only be used in instances where a particular TTL is desired;
  274.      * otherwise it is preferable to set a TTL once on the socket, and
  275.      * use that default TTL for all packets.  This method does <B>not
  276.      * </B> alter the default TTL for the socket.
  277.      *
  278.      * <p>If there is a security manager, this method first performs some
  279.      * security checks. First, if <code>p.getAddress().isMulticastAddress()</code>
  280.      * is true, this method calls the
  281.      * security manager's <code>checkMulticast</code> method
  282.      * with <code>p.getAddress()</code> and <code>ttl</code> as its arguments.
  283.      * If the evaluation of that expression is false,
  284.      * this method instead calls the security manager's 
  285.      * <code>checkConnect</code> method with arguments
  286.      * <code>p.getAddress().getHostAddress()</code> and
  287.      * <code>p.getPort()</code>. Each call to a security manager method
  288.      * could result in a SecurityException if the operation is not allowed.
  289.      * 
  290.      * @param p    is the packet to be sent. The packet should contain
  291.      * the destination multicast ip address and the data to be sent.
  292.      * One does not need to be the member of the group to send
  293.      * packets to a destination multicast address.
  294.      * @param ttl optional time to live for multicast packet.
  295.      * default ttl is 1.
  296.      * 
  297.      * @exception IOException is raised if an error occurs i.e
  298.      * error while setting ttl.
  299.      * @exception  SecurityException  if a security manager exists and its  
  300.      *             <code>checkMulticast</code> or <code>checkConnect</code> 
  301.      *             method doesn't allow the send.
  302.      * 
  303.      * @see DatagramSocket#send
  304.      * @see DatagramSocket#receive
  305.      * @see SecurityManager#checkMulticast(java.net.InetAddress, byte)
  306.      * @see SecurityManager#checkConnect
  307.      */
  308.     public void send(DatagramPacket p, byte ttl)
  309.         throws IOException {
  310.             synchronized(ttlLock) {
  311.                 synchronized(p) {
  312.             if (!connected) {
  313.                         // Security manager makes sure that the multicast address
  314.                         // is allowed one and that the ttl used is less
  315.                         // than the allowed maxttl.
  316.                         SecurityManager security = System.getSecurityManager();
  317.                         if (security != null) {
  318.                             if (p.getAddress().isMulticastAddress()) {
  319.                                 security.checkMulticast(p.getAddress(), ttl);
  320.                             } else {
  321.                                 security.checkConnect(p.getAddress().getHostAddress(),
  322.                                                       p.getPort());
  323.                             }
  324.                         }
  325.             } else {
  326.             // we're connected
  327.             InetAddress packetAddress = null;
  328.             packetAddress = p.getAddress();
  329.             if (packetAddress == null) {
  330.                 p.setAddress(connectedAddress);
  331.                 p.setPort(connectedPort);
  332.             } else if ((!packetAddress.equals(connectedAddress)) ||
  333.                    p.getPort() != connectedPort) {
  334.                 throw new SecurityException("connected address and packet address" +
  335.                             " differ");
  336.             }
  337.             }
  338.                     byte dttl = getTTL();
  339.                     try {
  340.                         if (ttl != dttl) {
  341.                             // set the ttl
  342.                             impl.setTTL(ttl);
  343.                         }
  344.                         // call the datagram method to send
  345.                         impl.send(p);
  346.                     } finally {
  347.                         // set it back to default
  348.                         if (ttl != dttl) {
  349.                             impl.setTTL(dttl);
  350.                         }
  351.                     }
  352.                 } // synch p
  353.             }  //synch ttl
  354.     } //method
  355. }
  356.