559e81b1ff5b9eac8195b0d70ed56e2f2b84235a
[WeStealzYourDataz.git] / src / uk / ac / ntu / n0521366 / wsyd / libs / net / NetworkServerUDPMulticast.java
1 /*
2  * The MIT License
3  *
4  * Copyright 2015 TJ <hacker@iam.tj>.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 package uk.ac.ntu.n0521366.wsyd.libs.net;
25
26 import java.io.IOException;
27 import java.net.MulticastSocket;
28 import java.net.SocketException;
29 import java.net.NetworkInterface;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32 import java.util.ArrayList;
33 import java.util.Enumeration;
34 import uk.ac.ntu.n0521366.wsyd.libs.net.ServiceAddressMap;
35
36 /**
37  *
38  * @author TJ <hacker@iam.tj>
39  */
40 public class NetworkServerUDPMulticast extends NetworkServerUDP {
41     
42     /**
43      * the Multicast socket.
44      * 
45      * Deliberately hides the DatagramSocket in NetworkServerUDP so that inherited methods
46      * can access the same name.
47      */
48     private MulticastSocket _multicastSocket = null;
49     /**
50      * Construct the server with a Logger.
51      * 
52      * No socket is opened.
53      * 
54      * @param socketAddress The socket to listen on
55      * @param title source identifier for use in log messages and sent NetworkMessage objects
56      * @param serviceToHostMap the map object used for host <> InetSocketAddress lookups
57      * @param logger An instance of Logger to be used by all objects of this class
58      */
59     public NetworkServerUDPMulticast(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap, Logger logger) {
60         super(socketAddress, title, serviceToHostMap, logger);
61         // permit broadcasting to pseudo-host 'all' since this is multicast
62         this._serviceToHostMap.put("all", new ServiceAddressMap.LastSeenHost(socketAddress.getSocketAddress()));
63     }
64
65     /**
66      * Construct the server without a Logger.
67      * 
68      * No socket is opened.
69      * 
70      * @param socketAddress The socket to listen on
71      * @param title source identifier for use in log messages and sent NetworkMessage objects
72      * @param serviceToHostMap the map object used for host <> InetSocketAddress lookups
73      */
74     public NetworkServerUDPMulticast(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap) {
75         super(socketAddress, title, serviceToHostMap);
76     }
77
78     /**
79      * Get the MulticastSocket object for this service.
80      * 
81      * @return the base-class DatagramSocket type
82      */
83     @Override
84     public java.net.DatagramSocket getSocket() {
85         return this._multicastSocket;
86     }
87     /**
88      * Join the multicast group on all interfaces ready for accepting packets.
89      * 
90      * It should also set a reasonable socket timeout with a call to setSoTimeout()
91      * to prevent unnecessary blocking.
92      * 
93      * @throws SocketException 
94      */
95     @Override
96     public  void serverOpen() throws SocketException {
97         try {
98             ArrayList<String> messages = new ArrayList<>();
99
100             this._multicastSocket = new MulticastSocket(_socketAddress.getPort());
101             this._multicastSocket.setTimeToLive(2); // don't traverse more than 2 routers
102             this._multicastSocket.setSoTimeout(100); // 1/10th second blocking timeout on receive()
103             this._multicastSocket.setLoopbackMode(true); // inverted logic; true == disable. Don't want to receive our own sent packets
104             
105             Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
106             while (ifs.hasMoreElements()) {
107                 NetworkInterface iface = ifs.nextElement();
108                 messages.clear();
109                 messages.add(iface.getName());
110                 messages.add(Boolean.toString(iface.supportsMulticast()));
111                 log(Level.INFO, _title, "Interface {0}: probe multicast support: {1}", messages);
112                 if (iface.supportsMulticast()) {
113                     try {
114                         messages.clear();
115                         messages.add(iface.getName());
116                         messages.add(_socketAddress.getSocketAddress().getAddress().toString());
117                         this._multicastSocket.joinGroup(_socketAddress.getSocketAddress(), iface);
118                     log(Level.INFO, _title, "Interface {0}: joined multicast group {1}", messages);
119                     } catch (Exception e) {
120                         messages.clear();
121                         messages.add(iface.getName());
122                         log(Level.SEVERE, _title, "Interface {0}: failed to join multicast group", messages);
123                     }
124                 }
125             }
126         } catch (IOException e) {
127             log(Level.SEVERE, _title, "Failed to open multicast socket");
128         }
129     }
130
131     /**
132      * Close the socket.
133      * 
134      * @throws SocketException
135      */
136     @Override
137     public void serverClose() throws SocketException {
138         if (this._multicastSocket != null) {
139             try {
140                 log(Level.INFO, _title, "Leaving multicast group");
141                 this._multicastSocket.leaveGroup(_socketAddress.getAddress());
142                 this._multicastSocket.close();
143             } catch (IOException e) {
144                 log(Level.SEVERE, _title, "failed to leave multicast group");
145             }
146             
147         }
148     }
149 }