Example usage for java.net MulticastSocket MulticastSocket

List of usage examples for java.net MulticastSocket MulticastSocket

Introduction

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

Prototype

public MulticastSocket(SocketAddress bindaddr) throws IOException 

Source Link

Document

Create a MulticastSocket bound to the specified socket address.

Usage

From source file:com.cafbit.multicasttest.NetThread.java

/**
 * Open a multicast socket on the mDNS address and port.
 * @throws IOException/*  w w  w. j a  v  a 2 s.c o m*/
 */
private void openSocket() throws IOException {
    Log.i(TAG, "OpenScoket");
    multicastSocket = new MulticastSocket(MDNS_PORT);
    multicastSocket.setTimeToLive(255);
    multicastSocket.setReuseAddress(true);
    multicastSocket.setNetworkInterface(networkInterface);
    multicastSocket.joinGroup(groupAddress);
}

From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java

/**
 * Broadcasts a SSDP discovery message into the network to find provided
 * services./*from   ww w .ja v a  2s.c  o m*/
 * 
 * @return The Socket the answers will arrive at.
 * @throws UnknownHostException
 * @throws IOException
 * @throws SocketException
 * @throws UnsupportedEncodingException
 */
private MulticastSocket sendDiscoveryBroacast()
        throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException {
    InetAddress multicastAddress = InetAddress.getByName("239.255.255.250");
    final int port = 1900;
    MulticastSocket socket = new MulticastSocket(port);
    socket.setReuseAddress(true);
    socket.setSoTimeout(130000);
    socket.joinGroup(multicastAddress);
    byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8");
    DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, multicastAddress,
            port);
    socket.send(datagramPacket);
    return socket;
}

From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java

/**
 * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called.
 * @param listener listener to notify of events
 * @throws IOException if socket error occurs
 * @throws NullPointerException if any argument is {@code null}
 *///from  w w w  .j ava  2s  .  co m
public void start(NatPmpEventListener listener) throws IOException {
    Validate.notNull(listener);

    MulticastSocket socket = null;
    try {
        final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD
        final int port = 5350;
        final InetSocketAddress groupAddress = new InetSocketAddress(group, port);

        socket = new MulticastSocket(port);

        if (!currentSocket.compareAndSet(null, socket)) {
            IOUtils.closeQuietly(socket);
            return;
        }

        socket.setReuseAddress(true);

        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
                InetAddress addr = addrs.nextElement();

                try {
                    if (addr instanceof Inet4Address) {
                        socket.joinGroup(groupAddress, networkInterface);
                    }
                } catch (IOException ioe) { // NOPMD
                    // occurs with certain interfaces
                    // do nothing
                }
            }
        }

        ByteBuffer buffer = ByteBuffer.allocate(12);
        DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity());

        while (true) {
            buffer.clear();
            socket.receive(data);
            buffer.position(data.getLength());
            buffer.flip();

            if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore
                continue;
            }

            if (buffer.remaining() != 12) { // data isn't the expected size, ignore
                continue;
            }

            int version = buffer.get(0);
            if (version != 0) { // data doesn't have the correct version, ignore
                continue;
            }

            int opcode = buffer.get(1) & 0xFF;
            if (opcode != 128) { // data doesn't have the correct op, ignore
                continue;
            }

            int resultCode = buffer.getShort(2) & 0xFFFF;
            switch (resultCode) {
            case 0:
                break;
            default:
                continue; // data doesn't have a successful result, ignore
            }

            listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer));
        }

    } catch (IOException ioe) {
        if (currentSocket.get() == null) {
            return; // ioexception caused by interruption/stop, so just return without propogating error up
        }

        throw ioe;
    } finally {
        IOUtils.closeQuietly(socket);
        currentSocket.set(null);
    }
}

From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {// w  w  w . j  av  a2s . co m
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}

From source file:ws.argo.mcg.GatewayReceiver.java

boolean joinGroup() {
    boolean success = true;
    InetSocketAddress socketAddress = new InetSocketAddress(multicastAddress, multicastPort);
    try {//from  w  ww.j  av  a2s  .c  om
        // Setup for incoming multicast requests
        maddress = InetAddress.getByName(multicastAddress);

        if (niName != null)
            ni = NetworkInterface.getByName(niName);

        if (ni == null) {
            InetAddress localhost = InetAddress.getLocalHost();
            LOGGER.fine("Network Interface name not specified.  Using the NI for localhost "
                    + localhost.getHostAddress());
            ni = NetworkInterface.getByInetAddress(localhost);
        }

        this.outboundSocket = new MulticastSocket(multicastPort);
        // for some reason NI is still NULL. Check /etc/hosts
        if (ni == null) {
            this.outboundSocket.joinGroup(maddress);
            LOGGER.warning(
                    "Unable to determine the network interface for the localhost address.  Check /etc/hosts for wierd entry like 127.0.1.1 mapped to DNS name.");
            LOGGER.info("Unknown network interface joined group " + socketAddress.toString());
        } else {
            this.outboundSocket.joinGroup(socketAddress, ni);
            LOGGER.info(ni.getName() + " joined group " + socketAddress.toString());
        }
    } catch (IOException e) {
        StringBuffer buf = new StringBuffer();
        try {
            buf.append("(lb:" + this.ni.isLoopback() + " ");
        } catch (SocketException e2) {
            buf.append("(lb:err ");
        }
        try {
            buf.append("m:" + this.ni.supportsMulticast() + " ");
        } catch (SocketException e3) {
            buf.append("(m:err ");
        }
        try {
            buf.append("p2p:" + this.ni.isPointToPoint() + " ");
        } catch (SocketException e1) {
            buf.append("p2p:err ");
        }
        try {
            buf.append("up:" + this.ni.isUp() + " ");
        } catch (SocketException e1) {
            buf.append("up:err ");
        }
        buf.append("v:" + this.ni.isVirtual() + ") ");

        System.out.println(this.ni.getName() + " " + buf.toString() + ": could not join group "
                + socketAddress.toString() + " --> " + e.toString());

        success = false;
    }
    return success;
}

From source file:org.lwes.listener.DatagramEnqueuer.java

@Override
public void initialize() throws IOException {
    if (address == null) {
        address = InetAddress.getByName(DEFAULT_ADDRESS);
    }/*  w w  w .j ava2 s .  com*/

    if (address.isMulticastAddress()) {
        socket = new MulticastSocket(port);
        ((MulticastSocket) socket).setTimeToLive(ttl);
        if (iface != null) {
            ((MulticastSocket) socket).setInterface(iface);
        }
        ((MulticastSocket) socket).joinGroup(address);
    } else {
        if (iface != null) {
            socket = new DatagramSocket(port, iface);
        } else {
            socket = new DatagramSocket(port, address);
        }

        if (port == 0) {
            port = socket.getLocalPort();
        }
    }
    int bufSize = MAX_DATAGRAM_SIZE * 50;
    String bufSizeStr = System.getProperty("MulticastReceiveBufferSize");
    if (bufSizeStr != null && !"".equals(bufSizeStr)) {
        bufSize = Integer.parseInt(bufSizeStr);
    }
    socket.setReceiveBufferSize(bufSize);
}

From source file:ws.argo.mcg.GatewaySender.java

boolean joinGroup() {
    boolean success = true;
    InetSocketAddress socketAddress = new InetSocketAddress(multicastAddress, multicastPort);
    try {//from  w w  w  .  j  a v a  2 s  .  c  om
        // Setup for incoming multicast requests

        maddress = InetAddress.getByName(multicastAddress);

        if (niName != null)
            ni = NetworkInterface.getByName(niName);
        if (ni == null) {
            InetAddress localhost = InetAddress.getLocalHost();
            LOGGER.fine("Network Interface name not specified or incorrect.  Using the NI for localhost "
                    + localhost.getHostAddress());
            ni = NetworkInterface.getByInetAddress(localhost);
        }

        LOGGER.info("Starting GatewaySender:  Receiving mulitcast @ " + multicastAddress + ":" + multicastPort
                + " -- Sending unicast @ " + unicastAddress + ":" + unicastPort);
        this.inboundSocket = new MulticastSocket(multicastPort);
        if (ni == null) { // for some reason NI is still NULL. Not sure why this
                          // happens.
            this.inboundSocket.joinGroup(maddress);
            LOGGER.warning(
                    "Unable to determine the network interface for the localhost address. Check /etc/hosts for weird entry like 127.0.1.1 mapped to DNS name.");
            LOGGER.info("Unknown network interface joined group " + socketAddress.toString());
        } else {
            this.inboundSocket.joinGroup(socketAddress, ni);
            LOGGER.info(ni.getName() + " joined group " + socketAddress.toString());
        }

    } catch (IOException e) {
        StringBuffer buf = new StringBuffer();
        try {
            buf.append("(lb:" + this.ni.isLoopback() + " ");
        } catch (SocketException e2) {
            buf.append("(lb:err ");
        }
        try {
            buf.append("m:" + this.ni.supportsMulticast() + " ");
        } catch (SocketException e3) {
            buf.append("(m:err ");
        }
        try {
            buf.append("p2p:" + this.ni.isPointToPoint() + " ");
        } catch (SocketException e1) {
            buf.append("p2p:err ");
        }
        try {
            buf.append("up:" + this.ni.isUp() + " ");
        } catch (SocketException e1) {
            buf.append("up:err ");
        }
        buf.append("v:" + this.ni.isVirtual() + ") ");

        System.out.println(this.ni.getName() + " " + buf.toString() + ": could not join group "
                + socketAddress.toString() + " --> " + e.toString());

        success = false;
    }
    return success;
}

From source file:org.apache.jcs.auxiliary.lateral.socket.tcp.discovery.UDPDiscoveryReceiver.java

/**
 * Creates the socket for this class.//from  w w w  .j a  va2  s . com
 *
 * @param multicastAddressString
 * @param multicastPort
 * @throws IOException
 */
private void createSocket(String multicastAddressString, int multicastPort) throws IOException {
    try {
        m_socket = new MulticastSocket(multicastPort);
        m_socket.joinGroup(InetAddress.getByName(multicastAddressString));
    } catch (IOException e) {
        log.error("Could not bind to multicast address [" + multicastAddressString + ":" + multicastPort + "]",
                e);
        throw e;
    }
}

From source file:com.lfv.yada.net.client.ClientNetworkManager.java

public ClientNetworkManager(int terminalId, ClientBundle bundle, SocketAddress serverSocketAddr,
        SocketAddress localhostBindSocketAddr, SocketAddress multicastSocketAddr, int multicastTTL,
        TerminalProperties properties) throws IOException {

    // Create a logger for this class
    log = LogFactory.getLog(getClass());

    // Load terminal properties
    this.properties = properties;

    // Setup stuff
    this.terminalId = terminalId;
    this.bundle = bundle;
    this.serverSocketAddr = new SocketAddress(serverSocketAddr);

    // Resolve local host address
    InetAddress localHost = getLocalHostFix();
    if (localHost == null) {
        localHost = InetAddress.getLocalHost();
        if (localHost == null)
            throw new UnknownHostException("Could not resolve ip address of localhost");
    }/*from  ww  w  . j  a v a 2 s  .co  m*/

    // The socket to be used for sending and receiving unicast packets
    DatagramSocket usocket;
    if (localhostBindSocketAddr.getAddress() == 0)
        usocket = new DatagramSocket();
    else
        usocket = new DatagramSocket(localhostBindSocketAddr.getPort(),
                localhostBindSocketAddr.getInetAddress());

    // The multicast socket
    InetAddress maddr = multicastSocketAddr.getInetAddress();
    int mport = multicastSocketAddr.getPort();
    MulticastSocket msocket = null;

    multicastAvailable = (maddr != null && mport > 0);
    if (multicastAvailable) {
        msocket = new MulticastSocket(mport);
        try {
            msocket.joinGroup(maddr);
            msocket.setTimeToLive(multicastTTL);
        } catch (SocketException ex) {
            log.warn("!!!");
            log.warn("!!! Unable to create multicast socket! Multicasting has been disabled!");
            log.warn("!!! On linux systems a default gateway must be defined, try:");
            log.warn("!!! > route add default gw <some_ip_address>");
            log.warn("!!!");
            msocket = null;
            multicastAvailable = false;
        }
    } else
        log.warn("No multicast address or port defined, multicasting has been disabled!");

    // Store the local unicast ip address and port
    localSocketAddr = new SocketAddress(localHost, usocket.getLocalPort());

    // Create a receiver and a sender (send/recv must use the same port number)
    receiver = new ClientPacketReceiver(terminalId, usocket, msocket);
    sender = new ClientPacketSender(usocket, msocket, multicastSocketAddr);

    // Create a transaction mananger
    transactionManager = new TransactionManager(sender);
    receiver.setControlPacketDispatcher(transactionManager);
    receiver.setSendPacketDispatcher(sender);

    // Create a timer for handling pings
    timer = new Timer("Snetworkmanager", true);

    // Initialize packet pool
    PacketPool.getPool();

    // Setup request handlers
    transactionManager.setRequestHandler(Packet.SESSION, new SessionRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.UPDATE, new UpdateRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INFO, new InfoRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.ISA, new IsaRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.CONNECT, new ConnectRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INITIATE, new InitiateRequestPacketHandler());
}

From source file:net.di2e.ddf.argo.probe.responder.ProbeResponder.java

private void startSocket(int port, String address) throws IOException {
    if (socket != null && socket.isConnected()) {
        LOGGER.debug("Cannot try to connect an already connected socket.");
        return;//from w  w w . j a  va  2s .  c o  m
    } else {
        LOGGER.debug("Starting up multicast socket listener at {}:{}", address, port);
        socket = new MulticastSocket(port);
        socket.joinGroup(InetAddress.getByName(address));
    }
}