233fc34f70a3f56f3034ce20500accea14eee649
[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     }
62
63     /**
64      * Construct the server without a Logger.
65      * 
66      * No socket is opened.
67      * 
68      * @param socketAddress The socket to listen on
69      * @param title source identifier for use in log messages and sent NetworkMessage objects
70      * @param serviceToHostMap the map object used for host <> InetSocketAddress lookups
71      */
72     public NetworkServerUDPMulticast(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap) {
73         super(socketAddress, title, serviceToHostMap);
74     }
75
76     /**
77      * Get the MulticastSocket object for this service.
78      * 
79      * @return the base-class DatagramSocket type
80      */
81     @Override
82     public java.net.DatagramSocket getSocket() {
83         return this._multicastSocket;
84     }
85     /**
86      * Join the multicast group on all interfaces ready for accepting packets.
87      * 
88      * It should also set a reasonable socket timeout with a call to setSoTimeout()
89      * to prevent unnecessary blocking.
90      * 
91      * @throws SocketException 
92      */
93     @Override
94     public  void serverOpen() throws SocketException {
95         try {
96             ArrayList<String> messages = new ArrayList<>();
97
98             this._multicastSocket = new MulticastSocket(_socketAddress.getPort());
99             this._multicastSocket.setTimeToLive(2); // don't traverse more than 2 routers
100             this._multicastSocket.setSoTimeout(100); // 1/10th second blocking timeout on receive()
101             this._multicastSocket.setLoopbackMode(true); // inverted logic; true == disable. Don't want to receive our own sent packets
102             
103             Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
104             while (ifs.hasMoreElements()) {
105                 NetworkInterface iface = ifs.nextElement();
106                 messages.clear();
107                 messages.add(iface.getName());
108                 messages.add(Boolean.toString(iface.supportsMulticast()));
109                 log(Level.INFO, _title, "Interface {0}: probe multicast support: {1}", messages);
110                 if (iface.supportsMulticast()) {
111                     try {
112                         messages.clear();
113                         messages.add(iface.getName());
114                         messages.add(_socketAddress.getSocketAddress().getAddress().toString());
115                         this._multicastSocket.joinGroup(_socketAddress.getSocketAddress(), iface);
116                     log(Level.INFO, _title, "Interface {0}: joined multicast group {1}", messages);
117                     } catch (Exception e) {
118                         messages.clear();
119                         messages.add(iface.getName());
120                         log(Level.SEVERE, _title, "Interface {0}: failed to join multicast group", messages);
121                     }
122                 }
123             }
124         } catch (IOException e) {
125             log(Level.SEVERE, _title, "Failed to open multicast socket");
126         }
127     }
128
129     /**
130      * Close the socket.
131      * 
132      * @throws SocketException
133      */
134     @Override
135     public void serverClose() throws SocketException {
136         if (this._multicastSocket != null) {
137             try {
138                 log(Level.INFO, _title, "Leaving multicast group");
139                 this._multicastSocket.leaveGroup(_socketAddress.getAddress());
140                 this._multicastSocket.close();
141             } catch (IOException e) {
142                 log(Level.SEVERE, _title, "failed to leave multicast group");
143             }
144             
145         }
146     }
147 }