Example usage for java.net DatagramSocket send

List of usage examples for java.net DatagramSocket send

Introduction

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

Prototype

public void send(DatagramPacket p) throws IOException 

Source Link

Document

Sends a datagram packet from this socket.

Usage

From source file:org.cc86.MMC.client.Main.java

public static String serverDiscovery() {
    String res = "0.0.0.0";
    DatagramSocket c;
    // Find the server using UDP broadcast
    try {//from www. j a  v a2  s. c om
        //Open a random port to send the package
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 0xCC86);
            c.send(sendPacket);
            l.info("Request packet sent to: 255.255.255.255 (DEFAULT)");
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }

                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }

                l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: "
                        + networkInterface.getDisplayName());
            }
        }

        l.info("Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_MMC_RESPONSE")) {
            //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            res = (receivePacket.getAddress() + "").substring(1);
        }

        //Close the port!
        c.close();
    } catch (IOException ex) {

    }
    return res;
}

From source file:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java

/**
 * [Topic] getTopic?????UDP???/*  w  w  w  .  j  ava  2s  .co  m*/
 * @param facilityId
 */
private static void awakeAgent(String facilityId) {
    String ipAddress = "";
    Integer port = 24005;
    m_log.debug("awakeAgent facilityId=" + facilityId);
    try {
        NodeInfo info = NodeProperty.getProperty(facilityId);
        ipAddress = info.getAvailableIpAddress();
        port = info.getAgentAwakePort();
    } catch (FacilityNotFound e) {
        m_log.debug(e.getMessage(), e);
        return;
    } catch (Exception e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        return;
    }
    if (port < 1 || 65535 < port) {
        m_log.info("awakeAgent : invalid port " + port + "(" + facilityId + ")");
    }
    m_log.debug("awakeAgent ipaddress=" + ipAddress);

    final int BUFSIZE = 1;
    byte[] buf = new byte[BUFSIZE];
    buf[0] = 1;
    InetAddress sAddr;
    try {
        sAddr = InetAddress.getByName(ipAddress);
    } catch (UnknownHostException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        return;
    }
    DatagramPacket sendPacket = new DatagramPacket(buf, BUFSIZE, sAddr, port);
    DatagramSocket soc = null;
    try {
        soc = new DatagramSocket();
        soc.send(sendPacket);
    } catch (SocketException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
    } catch (IOException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
    } finally {
        if (soc != null) {
            soc.close();
        }
    }
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Send reply./*w w w .ja v  a  2  s  .  com*/
 *
 * @param host the host
 * @param port the port
 * @param msg the msg
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void sendReply(String host, int port, String msg) {
    DatagramSocket datagramSocket = null;

    try {
        datagramSocket = new DatagramSocket();
        InetAddress inetAddr = InetAddress.getByName(host);
        DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), inetAddr, port);

        logger.trace(
                "Sending this reply [" + host + ":" + port + "]: " + StringUtils.replace(msg, CRLF, "<CRLF>"));

        datagramSocket.send(dgmPacket);
    } catch (Exception e) {
        logger.info(e.getMessage());
        logger.debug("Error sending reply", e);
    } finally {
        if (datagramSocket != null) {
            datagramSocket.close();
        }
    }
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Send the provided message to the socket.
 *
 * @param socket the socket/*from   w w  w. j a  v  a 2 s  . co  m*/
 * @param nt the nt
 * @param message the message
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void sendMessage(DatagramSocket socket, String nt, String message) throws IOException {
    String msg = buildMsg(nt, message);
    //Random rand = new Random();

    // logger.trace( "Sending this SSDP packet: " + CRLF + StringUtils.replace(msg, CRLF, "<CRLF>")));

    InetAddress upnpAddress = getUPNPAddress();
    DatagramPacket ssdpPacket = new DatagramPacket(msg.getBytes(), msg.length(), upnpAddress, UPNP_PORT);
    socket.send(ssdpPacket);

    // XXX Why is it necessary to sleep for this random time? What would happen when random equals 0?
    //sleep(rand.nextInt(1800 / 2));

    // XXX Why send the same packet twice?
    //socket.send(ssdpPacket);

    // XXX Why is it necessary to sleep for this random time (again)?
    //sleep(rand.nextInt(1800 / 2));
}

From source file:com.t_oster.visicut.misc.Helper.java

public static List<String> findVisiCamInstances() {
    List<String> result = new LinkedList<String>();
    // Find the server using UDP broadcast
    try {//  w w w .j a va  2s .c o  m
        //Open a random port to send the package
        DatagramSocket c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "VisiCamDiscover".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 8888);
            c.send(sendPacket);
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }
                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }
            }
        }
        //Wait for a response
        byte[] recvBuf = new byte[15000];
        c.setSoTimeout(3000);
        while (true) {
            DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
            try {
                c.receive(receivePacket);
                //Check if the message is correct
                String message = new String(receivePacket.getData()).trim();
                //Close the port!
                c.close();
                if (message.startsWith("http")) {
                    result.add(message);
                }
            } catch (SocketTimeoutException e) {
                break;
            }
        }
    } catch (IOException ex) {
    }
    return result;
}

From source file:uk.co.ghosty.phonegap.plugins.WakeOnLan.java

@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
    // TODO Auto-generated method stub
    Log.d("WakeOnLan", "Calling plugin execute message");
    PluginResult result = null;/*w ww  .j  a v  a 2  s.c  o  m*/
    if (ACTION.equals(action)) {
        try {
            String macStr = data.getString(0);
            String ipStr = data.getString(1);

            byte[] macBytes = getMacBytes(macStr);
            byte[] bytes = new byte[6 + 16 * macBytes.length];

            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) 0xff;
            }
            for (int i = 6; i < bytes.length; i += macBytes.length) {
                System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
            }

            InetAddress address = InetAddress.getByName(ipStr);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
            socket.close();

            System.out.println("Wake-on-LAN packet sent.");
            result = new PluginResult(Status.OK, "Packet sent");
        } catch (Exception e) {
            result = new PluginResult(Status.IO_EXCEPTION);
            Log.e("WakeOnLan", "Exception thrown", e);
        }
    } else {
        result = new PluginResult(Status.INVALID_ACTION);
        Log.d("DirectoryListPlugin", "Invalid action : " + action + " passed");
    }
    return result;
}

From source file:org.mule.test.firewall.FirewallTestCase.java

protected void doTestUdp(InetAddress address, int port) throws Exception {
    try {// w ww.  j  a  va2 s  .c  o  m
        logger.debug("Testing UDP on " + addressToString(address, port));
        DatagramSocket server = openUdpServer(address, port);
        DatagramSocket client = openUdpClient();
        client.send(new DatagramPacket(new byte[] { 1 }, 1, address, port));
        DatagramPacket packet = new DatagramPacket(new byte[1], 1);
        server.receive(packet);
        assertEquals("Failed to send packet via " + addressToString(address, port), 1, packet.getData()[0]);
        client.close();
        server.close();
    } catch (Exception e) {
        logger.error("Error while attempting UDP message on " + addressToString(address, port));
        throw e;
    }
}

From source file:org.openhab.binding.wol.internal.WolBinding.java

private void sendWolPacket(WolBindingConfig config) {

    if (config == null) {
        logger.error("given parameter 'config' must not be null");
        return;//from ww w  .  java2  s  . c  o m
    }

    InetAddress address = config.address;
    byte[] macBytes = config.macBytes;

    try {

        byte[] bytes = fillMagicBytes(macBytes);

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);

        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();

        logger.info("Wake-on-LAN packet sent [broadcastIp={}, macaddress={}]", address.getHostName(),
                String.valueOf(Hex.encodeHex(macBytes)));
    } catch (Exception e) {
        logger.error("Failed to send Wake-on-LAN packet [broadcastIp=" + address.getHostAddress()
                + ", macaddress=" + String.valueOf(Hex.encodeHex(macBytes)) + "]", e);
    }

}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testUdp() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);//from  w ww .  ja  va  2  s  .  c o  m
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    adapter.stop();
}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testAsMapFalse() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);//w w  w . j  a va 2s  . c  o m
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    DefaultMessageConverter defaultMessageConverter = new DefaultMessageConverter();
    defaultMessageConverter.setAsMap(false);
    adapter.setConverter(defaultMessageConverter);
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    assertEquals("<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE",
            new String((byte[]) message.getPayload(), "UTF-8"));
    adapter.stop();
}