Example usage for java.net MulticastSocket setInterface

List of usage examples for java.net MulticastSocket setInterface

Introduction

In this page you can find the example usage for java.net MulticastSocket setInterface.

Prototype

public void setInterface(InetAddress inf) throws SocketException 

Source Link

Document

Set the multicast network interface used by methods whose behavior would be affected by the value of the network interface.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("google.com"), port);

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);//from   w w w.  j a  va  2s  . c om
    }
    ms.setInterface(InetAddress.getByName("google.com"));

    ms.close();
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

private void sendHello(UPNPMBeanDevice dv) throws IOException {
    InetAddress group = InetAddress.getByName("239.255.255.250");
    java.net.MulticastSocket multi = new java.net.MulticastSocket(bindAddress.getPort());
    multi.setInterface(bindAddress.getAddress());
    multi.setTimeToLive(dv.getSSDPTTL());

    List packets = getReplyMessages(dv, true, dv.getSSDPAliveDelay());
    for (int i = 0; i < packets.size(); i++) {
        String packet = (String) packets.get(i);
        if (log.isDebugEnabled())
            log.debug("Sending ssdp alive message on 239.255.255.250:1900 multicast address:\n"
                    + packet.toString());
        byte[] pk = packet.getBytes();
        multi.send(new DatagramPacket(pk, pk.length, group, 1900));
    }//from w ww. j  av  a 2  s . c  om
    multi.close();
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

private void sendByeBye(UPNPMBeanDevice dv) throws IOException {
    InetAddress group = InetAddress.getByName("239.255.255.250");
    java.net.MulticastSocket multi = new java.net.MulticastSocket(bindAddress.getPort());
    multi.setInterface(bindAddress.getAddress());
    multi.setTimeToLive(dv.getSSDPTTL());

    List packets = getByeByeReplyMessages(dv);
    for (int i = 0; i < packets.size(); i++) {
        String packet = (String) packets.get(i);
        if (log.isDebugEnabled())
            log.debug("Sending ssdp:byebye message on 239.255.255.250:1900 multicast address:\n"
                    + packet.toString());
        byte[] pk = packet.getBytes();
        multi.send(new DatagramPacket(pk, pk.length, group, 1900));
    }//from  w ww.j av a  2 s.c  o m
    multi.close();
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

public void run() {
    InetAddress group = null;/*from   ww  w  . j  av  a 2  s. com*/
    try {
        group = InetAddress.getByName("239.255.255.250");
        skt = new java.net.MulticastSocket(1900);
        skt.setInterface(bindAddress.getAddress());
        skt.joinGroup(group);
    } catch (IOException ex) {
        log.error("Error during multicast socket creation, thread cannot start", ex);
        return;
    }
    isRunning = true;
    while (isRunning) {
        try {
            byte[] buffer = new byte[4096];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, bindAddress.getPort());
            skt.receive(packet);
            String received = new String(packet.getData(), 0, packet.getLength());
            if (log.isDebugEnabled())
                log.debug("Received message:\n" + received);
            HttpRequest req = new HttpRequest(received);
            if (req.getHttpCommand().equals("M-SEARCH")) {
                String man = req.getHTTPHeaderField("MAN");
                if (man.equals("\"ssdp:discover\"")) {
                    String searchTarget = req.getHTTPHeaderField("ST");
                    // TODO check ALL devices search target
                    //if ( searchTarget.equals( Discovery.ALL_DEVICES ) ) {
                    if (searchTarget.equals(Discovery.ROOT_DEVICES)) {
                        java.net.MulticastSocket multi = new java.net.MulticastSocket();
                        multi.setInterface(bindAddress.getAddress());
                        for (Iterator i = handledDevices.iterator(); i.hasNext();) {
                            UPNPMBeanDevice dv = (UPNPMBeanDevice) i.next();
                            List packets = getReplyMessages(dv, false, dv.getSSDPAliveDelay());
                            for (int z = 0; z < packets.size(); z++) {
                                String pack = (String) packets.get(z);
                                if (log.isDebugEnabled())
                                    log.debug("Sending http reply message on " + packet.getAddress() + ":"
                                            + packet.getPort() + " multicast address:\n" + pack.toString());
                                byte[] pk = pack.getBytes();
                                multi.setTimeToLive(dv.getSSDPTTL());
                                multi.send(new DatagramPacket(pk, pk.length, packet.getAddress(),
                                        packet.getPort()));
                            }
                        }
                        multi.close();
                    } else {
                        // TODO check a specific search target
                    }
                }
            }
        } catch (IOException ex) {
            if (isRunning) {
                log.error("Error during multicast socket IO operations", ex);
            }
        }
    }
}

From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java

@Test
public void verifySendMulticast() throws Exception {
    MulticastSocket socket;//from  w w w.  j  a va2 s  .c o m
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final String multicastAddress = this.multicastRule.getGroup();
    final String payload = "foo";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch received = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[8];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.close();
            byte[] src = receivedPacket.getData();
            int length = receivedPacket.getLength();
            int offset = receivedPacket.getOffset();
            byte[] dest = new byte[length];
            System.arraycopy(src, offset, dest, 0, length);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            received.countDown();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.afterPropertiesSet();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(received.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}

From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;/* ww w  . j a  va  2s  .  c  o  m*/
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final AtomicInteger ackPort = new AtomicInteger();

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch ackListening = new CountDownLatch(1);
    final CountDownLatch ackSent = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[1000];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            socket1.setSoTimeout(8000);
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            assertTrue(ackListening.await(10, TimeUnit.SECONDS));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.close();
            byte[] src = receivedPacket.getData();
            int length = receivedPacket.getLength();
            int offset = receivedPacket.getOffset();
            byte[] dest = new byte[6];
            System.arraycopy(src, offset + length - 6, dest, 0, 6);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
            mapper.setAcknowledge(true);
            mapper.setLengthCheck(true);
            Message<byte[]> message = mapper.toMessage(receivedPacket);
            Object id = message.getHeaders().get(IpHeaders.ACK_ID);
            byte[] ack = id.toString().getBytes();
            DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                    new InetSocketAddress(multicastRule.getNic(), ackPort.get()));
            DatagramSocket out = new DatagramSocket();
            out.send(ackPack);
            LogFactory.getLog(getClass())
                    .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress());
            out.close();
            ackSent.countDown();
            socket1.close();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort,
            true, true, "localhost", 0, 10000);
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.setMinAcksForSuccess(2);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    waitAckListening(handler);
    ackPort.set(handler.getAckPort());
    ackListening.countDown();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}