Java Code Examples for java.net.MulticastSocket#setTimeToLive()

The following examples show how to use java.net.MulticastSocket#setTimeToLive() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatagramIOImpl.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
synchronized public void init(InetAddress bindAddress, Router router, DatagramProcessor datagramProcessor) throws InitializationException {

        this.router = router;
        this.datagramProcessor = datagramProcessor;

        try {

            // TODO: UPNP VIOLATION: The spec does not prohibit using the 1900 port here again, however, the
            // Netgear ReadyNAS miniDLNA implementation will no longer answer if it has to send search response
            // back via UDP unicast to port 1900... so we use an ephemeral port
            log.info("Creating bound socket (for datagram input/output) on: " + bindAddress);
            localAddress = new InetSocketAddress(bindAddress, 0);
            socket = new MulticastSocket(localAddress);
            socket.setTimeToLive(configuration.getTimeToLive());
            socket.setReceiveBufferSize(262144); // Keep a backlog of incoming datagrams if we are not fast enough
        } catch (Exception ex) {
            throw new InitializationException("Could not initialize " + getClass().getSimpleName() + ": " + ex);
        }
    }
 
Example 2
Source File: TcpDiscoveryMulticastIpFinder.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Creates multicast socket and joins multicast group.
 *
 * @throws IOException If fails to create socket or join multicast group.
 * @return Multicast socket.
 */
private MulticastSocket createSocket() throws IOException {
    MulticastSocket sock = new MulticastSocket(mcastPort);

    sock.setLoopbackMode(false); // Use 'false' to enable support for more than one node on the same machine.

    if (sockItf != null)
        sock.setInterface(sockItf);

    if (sock.getLoopbackMode())
        U.warn(log, "Loopback mode is disabled which prevents nodes on the same machine from discovering " +
            "each other.");

    sock.joinGroup(mcastGrp);

    if (ttl != -1)
        sock.setTimeToLive(ttl);

    return sock;
}
 
Example 3
Source File: DatagramIOImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
synchronized public void init(InetAddress bindAddress, Router router, DatagramProcessor datagramProcessor) throws InitializationException {

        this.router = router;
        this.datagramProcessor = datagramProcessor;

        try {

            // TODO: UPNP VIOLATION: The spec does not prohibit using the 1900 port here again, however, the
            // Netgear ReadyNAS miniDLNA implementation will no longer answer if it has to send search response
            // back via UDP unicast to port 1900... so we use an ephemeral port
            log.info("Creating bound socket (for datagram input/output) on: " + bindAddress);
            localAddress = new InetSocketAddress(bindAddress, 0);
            socket = new MulticastSocket(localAddress);
            socket.setTimeToLive(configuration.getTimeToLive());
            socket.setReceiveBufferSize(262144); // Keep a backlog of incoming datagrams if we are not fast enough
        } catch (Exception ex) {
            throw new InitializationException("Could not initialize " + getClass().getSimpleName() + ": " + ex);
        }
    }
 
Example 4
Source File: CcuDiscoveryService.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private synchronized void startDiscovery() {
    try {
        logger.debug("Starting Homematic CCU discovery scan");
        String configuredBroadcastAddress = networkAddressService.getConfiguredBroadcastAddress();
        if (configuredBroadcastAddress != null) {
            broadcastAddress = InetAddress.getByName(configuredBroadcastAddress);
        }
        if (broadcastAddress == null) {
            logger.warn("Homematic CCU discovery: discovery not possible, no broadcast address found");
            return;
        }
        socket = new MulticastSocket();
        socket.setBroadcast(true);
        socket.setTimeToLive(5);
        socket.setSoTimeout(800);

        sendBroadcast();
        receiveResponses();
    } catch (Exception ex) {
        logger.error("An error was thrown while running Homematic CCU discovery {}", ex.getMessage(), ex);
    } finally {
        scanFuture = null;
    }
}
 
Example 5
Source File: MulticastDiscoveryAgent.java    From tomee with Apache License 2.0 6 votes vote down vote up
Multicast(final Tracker tracker) throws IOException {
    this.tracker = tracker;

    multicast = new MulticastSocket(port);
    multicast.setLoopbackMode(loopbackMode);
    multicast.setTimeToLive(timeToLive);
    multicast.joinGroup(address.getAddress());
    multicast.setSoTimeout((int) heartRate);

    listenerThread = new Thread(new Listener());
    listenerThread.setName("MulticastDiscovery: Listener");
    listenerThread.setDaemon(true);
    listenerThread.start();

    final Broadcaster broadcaster = new Broadcaster();

    timer = new Timer("MulticastDiscovery: Broadcaster", true);
    timer.scheduleAtFixedRate(broadcaster, 0, heartRate);

}
 
Example 6
Source File: SAdvertise.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Usage: SAdvertize localaddress multicastaddress port");
        System.out.println("java SAdvertize 10.16.88.178 224.0.1.105 23364");
        System.out.println("send from 10.16.88.178:23364 to 224.0.1.105:23364");
        System.exit(1);
    }
    InetAddress group = InetAddress.getByName(args[1]);
    InetAddress addr = InetAddress.getByName(args[0]);
    int port = Integer.parseInt(args[2]);
    InetSocketAddress addrs = new InetSocketAddress(addr, port);

    MulticastSocket s = new MulticastSocket(addrs);
    s.setTimeToLive(29);
    s.joinGroup(group);
    boolean ok = true;
    while (ok) {
        byte[] buf = new byte[1000];
        DatagramPacket recv = new DatagramPacket(buf, buf.length, group, port);
        System.out.println("sending from: " + addr);
        s.send(recv);
        Thread.currentThread().sleep(2000);
    }
    s.leaveGroup(group);
}
 
Example 7
Source File: UDPDiscoverySender.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor for the UDPDiscoverySender object
 * <p>
 * This sender can be used to send multiple messages.
 * <p>
 * When you are done sending, you should destroy the socket sender.
 * <p>
 * @param host
 * @param port
 * @param udpTTL the Datagram packet time-to-live
 * @throws IOException
 */
public UDPDiscoverySender( String host, int port, int udpTTL )
    throws IOException
{
    try
    {
        log.debug( "Constructing socket for sender on port [{0}]", port );
        localSocket = new MulticastSocket( port );
        if (udpTTL > 0)
        {
            log.debug( "Setting datagram TTL to [{0}]", udpTTL );
            localSocket.setTimeToLive(udpTTL);
        }

        // Remote address.
        multicastAddress = InetAddress.getByName( host );
    }
    catch ( IOException e )
    {
        log.error( "Could not bind to multicast address [{0}]", host, e );
        throw e;
    }

    this.multicastPort = port;
}
 
Example 8
Source File: RtpSocketUdp.java    From rtmp-rtsp-stream-client-java with Apache License 2.0 5 votes vote down vote up
public RtpSocketUdp(int videoSourcePort, int audioSourcePort) {
  try {
    multicastSocketVideo = new MulticastSocket(videoSourcePort);
    multicastSocketVideo.setTimeToLive(64);
    multicastSocketAudio = new MulticastSocket(audioSourcePort);
    multicastSocketAudio.setTimeToLive(64);
  } catch (IOException e) {
    Log.e(TAG, "Error", e);
  }
}
 
Example 9
Source File: SenderReportUdp.java    From rtmp-rtsp-stream-client-java with Apache License 2.0 5 votes vote down vote up
public SenderReportUdp(int videoSourcePort, int audioSourcePort) {
  super();
  try {
    multicastSocketVideo = new MulticastSocket(videoSourcePort);
    multicastSocketVideo.setTimeToLive(64);
    multicastSocketAudio = new MulticastSocket(audioSourcePort);
    multicastSocketAudio.setTimeToLive(64);
  } catch (IOException e) {
    Log.e(TAG, "Error", e);
  }
}
 
Example 10
Source File: UDP.java    From openvisualtraceroute with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void test() throws Exception {
	final String hostname = "google.com";
	final String localhost = "localhost";
	final MulticastSocket datagramSocket = new MulticastSocket();
	datagramSocket.setSoTimeout(10000);
	short ttl = 1;
	final InetAddress receiverAddress = InetAddress.getByName(hostname);
	while (ttl < 100) {
		try {
			byte[] buffer = "0123456789".getBytes();
			datagramSocket.setTimeToLive(ttl++);
			final DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, receiverAddress, 80);

			datagramSocket.send(sendPacket);

			buffer = new byte[10];
			final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);

			datagramSocket.receive(receivePacket);
			System.out.println("ttl=" + ttl + " address=" + receivePacket.getAddress().getHostAddress() + " data="
					+ new String(receivePacket.getData()));
			Thread.sleep(1000);
		} catch (final SocketTimeoutException e) {
			System.out.println("timeout ttl=" + ttl);
		}
	}
}
 
Example 11
Source File: UDPSenderThread.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * コンストラクタ.
 * @throws IOException ソケットの作成に失敗した場合に発生
 */
public UDPSenderThread() throws IOException {
    mSocket = new MulticastSocket();
    mSocket.setTimeToLive(64);
    mSocket.setSoTimeout(5000);
    mDatagramPacket = new DatagramPacket(new byte[1], 1);
}
 
Example 12
Source File: PlainMulticastSender.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates an array of sockets with TTL and network interface set.
 *
 * @param mcastTTL multicast TTL.
 * @return an array of multicast sockets to broadcast on.
 * @throws IOException if I/O error occurred while creating a multicast socket.
 * @noinspection SocketOpenedButNotSafelyClosed, ConstantConditions
 */
private static MulticastSocket[] createSockets(final int mcastTTL) throws IOException {

   Exception lastException = null; // Records last error in case we could not create any sockets
   final List<MulticastSocket> socketList = new ArrayList<MulticastSocket>(11);
   final Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
   while (enumeration.hasMoreElements()) {
      try {
         final NetworkInterface netIf = enumeration.nextElement();
         if (netIf.supportsMulticast()) {

            final MulticastSocket socket = new MulticastSocket(); // NOPMD
            socket.setTimeToLive(mcastTTL);
            socket.setNetworkInterface(netIf);
            socket.setSendBufferSize(SEND_BUFFER_SIZE);
            socketList.add(socket);
         }
      } catch (final Exception e) {

         lastException = e;
         ExceptionUtils.ignoreException(e, "continue to connect to those we can");
      }
   }
   if (socketList.isEmpty()) {
      throw new IOException("Could not create at least one multicast socket. Last error: " + lastException);
   }
   return socketList.toArray(new MulticastSocket[socketList.size()]);
}
 
Example 13
Source File: Multicast.java    From Bitcoin with Apache License 2.0 5 votes vote down vote up
public static void sendData(MulticastSocket s, int ourTTL, byte[] buffer) throws IOException {
    // Create a DatagramPacket 
    final DatagramPacket pack = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(GROUP), PORT);
    // Get the current TTL, set our TTL, do a send, reset the TTL  
    final int ttl = s.getTimeToLive(); 
    s.setTimeToLive(ourTTL); 
    s.send(pack); 
    s.setTimeToLive(ttl);
}
 
Example 14
Source File: UDPTransport.java    From mpegts-streamer with Apache License 2.0 5 votes vote down vote up
private UDPTransport(String address, int port, int ttl, int soTimeout) throws IOException {
	// InetSocketAddress
	inetSocketAddress = new InetSocketAddress(address, port);

	// Create the socket but we don't bind it as we are only going to send data
	// Note that we don't have to join the multicast group if we are only sending data and not receiving
	multicastSocket = new MulticastSocket();
	multicastSocket.setReuseAddress(true);
	multicastSocket.setSoTimeout(soTimeout);
	multicastSocket.setTimeToLive(ttl);
}
 
Example 15
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static MulticastSocket setUpSocket() throws IOException {
    MulticastSocket recSocket = new MulticastSocket(null);
    recSocket.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), PORT));
    recSocket.setTimeToLive(10);
    recSocket.setSoTimeout(1000);
    recSocket.setBroadcast(true);
    return recSocket;
}
 
Example 16
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static void sendNotify(String notifyMessage, InetAddress ia) throws Exception {
    MulticastSocket socket = new MulticastSocket(null);
    try {
        socket.bind(new InetSocketAddress(PORT));
        socket.setTimeToLive(4);
        byte[] data = notifyMessage.toString().getBytes();
        socket.send(new DatagramPacket(data, data.length, new InetSocketAddress(ia, PORT)));
    } catch (Exception e) {
        logger.error("sendNotify", e);
        throw e;
    } finally {
        socket.disconnect();
        socket.close();
    }
}