Example usage for java.net DatagramPacket DatagramPacket

List of usage examples for java.net DatagramPacket DatagramPacket

Introduction

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

Prototype

public DatagramPacket(byte buf[], int length, InetAddress address, int port) 

Source Link

Document

Constructs a datagram packet for sending packets of length length to the specified port number on the specified host.

Usage

From source file:org.opennms.netmgt.syslogd.SyslogdLoadIT.java

@Test
@Transactional//  w  ww.  j ava  2s. com
public void testNGSyslog() throws Exception {
    loadSyslogConfiguration("/etc/syslogd-syslogng-configuration.xml");

    startSyslogdJavaNet();

    m_eventCounter.anticipate();

    InetAddress address = InetAddress.getLocalHost();

    // handle an invalid packet
    byte[] bytes = "<34>main: 2010-08-19 localhost foo0: load test 0 on tty1\0".getBytes();
    DatagramPacket pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT);
    new SyslogConnectionHandlerDefaultImpl().handleSyslogConnection(new SyslogConnection(pkt, m_config));

    // handle a valid packet
    bytes = "<34>monkeysatemybrain!\0".getBytes();
    pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT);
    new SyslogConnectionHandlerDefaultImpl().handleSyslogConnection(new SyslogConnection(pkt, m_config));

    m_eventCounter.waitForFinish(120000);

    assertEquals(1, m_eventCounter.getCount());
}

From source file:com.all.landownloader.discovery.LanDiscoverySocket.java

public void reply(InetAddress address) throws IllegalArgumentException {
    try {// ww w.j a  v a  2  s .  co  m
        byte[] buf = createPacket(REPLY_MSG);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();
    } catch (IOException e) {
    }
}

From source file:com.all.landownloader.discovery.LanDiscoverySocket.java

private void announce() throws IllegalArgumentException {
    try {/* www.jav  a 2 s  . c o m*/
        byte[] buf = createPacket(ANNOUNCE_MSG);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, addressGroup, PORT);
        MulticastSocket socket = new MulticastSocket();
        socket.send(packet);
        packet = new DatagramPacket(buf, buf.length, broadcast, PORT);
        socket.send(packet);
        socket.close();
    } catch (Exception e) {
    }

}

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

public void run() {
    InetAddress group = null;/*from w  w w.j  a  v  a  2s.  c om*/
    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:com.all.landownloader.discovery.LanDiscoverySocket.java

public void announceDeath() throws IllegalArgumentException {
    try {// w  w w  .  j av  a  2s.  c  o m
        byte[] buf = createPacket(BYE_MSG);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, addressGroup, PORT);
        MulticastSocket socket = new MulticastSocket();
        socket.send(packet);
        packet = new DatagramPacket(buf, buf.length, broadcast, PORT);
        socket.send(packet);
        socket.close();
    } catch (IOException e) {
    }
}

From source file:org.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();/*w w w .ja v  a 2  s .c  o  m*/
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java

private int dtnResourcesRequest(Node node) throws WSIAdapterException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        int packetID = UNDEFINED_COAP_MESSAGE_ID;
        do { //while loop to avoid a packetID that exists in the array that is to be ignored!
            packetID = random.nextInt(65535) + 1;
        } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                || packetID == UNDEFINED_COAP_MESSAGE_ID);

        String msgString = Integer.toString(packetID) + "#" + node.getId() + "#" + RESOURCE_REQ + "#wkc";
        byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
        msgBytes = msgString.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.send(sendPacket);//  w  w w  .  ja  va 2  s .  c om
        clientSocket.close();
        requestMsgId = packetID;
        logger.info("Sent Request: " + msgString);
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}

From source file:com.clustercontrol.notify.util.SendSyslog.java

private void sendUdpMsg(InetAddress ipAddress, int port, String msg) throws IOException {
    DatagramSocket soc = null;//from w w w. j  a v  a  2 s . c  o  m
    try {
        // ??????
        soc = new DatagramSocket(); // ??
        DatagramPacket sendPacket = null; // 

        sendPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, ipAddress, port);
        soc.send(sendPacket);
    } finally {
        if (soc != null) {
            soc.close();
        }
    }
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java

private int dtnObservationRequest(Node node, Resource resource) throws VitroGatewayException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        String moteUriResource = "";
        if (MoteResource.containsValue(resource)) {
            //moteUriResource += MoteResource.getMoteUriResource(resource);
            String theResourceName = MoteResource.getMoteUriResource(resource);
            if (theResourceName == null) {
                logger.error("unsupported resource");
                return UNDEFINED_COAP_MESSAGE_ID;
            }/*from w w  w. j  a va  2  s .co  m*/
            // FOR TCS adapter, we prefer the TEMPERATURE_TCS
            // FOR WLAB and HAI we prefer the TEMPERATURE_ALT
            // we do this check because the getMoteUriResource is making a reverse lookup in the hashmap (where two keys point to the same resource)
            if (theResourceName.compareToIgnoreCase(MoteResource.TEMPERATURE_TCS) == 0) {
                theResourceName = MoteResource.TEMPERATURE_ALT;
            }
            moteUriResource += theResourceName;

            int packetID = UNDEFINED_COAP_MESSAGE_ID;
            do { //while loop to avoid a packetID that exists in the array that is to be ignored!
                packetID = random.nextInt(65535) + 1;
            } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                    || packetID == UNDEFINED_COAP_MESSAGE_ID);

            String msgString = packetID + "#" + node.getId() + "#" + RESOURCE_REQ + "#" + moteUriResource;
            byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
            msgBytes = msgString.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                    InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
            DatagramSocket clientSocket = new DatagramSocket();
            clientSocket.send(sendPacket);
            clientSocket.close();
            requestMsgId = packetID;
            logger.info("Sent Request: " + msgString);
        } else {
            logger.warn("No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
            throw new WSIAdapterException(
                    "No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
        }
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoapHAI.java

private int dtnObservationRequest(Node node, Resource resource) throws VitroGatewayException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        String moteUriResource = "";
        if (MoteResource.containsValue(resource)) {
            //moteUriResource += MoteResource.getMoteUriResource(resource);
            String theResourceName = MoteResource.getMoteUriResource(resource);
            if (theResourceName == null) {
                logger.error("unsupported resource");
                return UNDEFINED_COAP_MESSAGE_ID;
            }//from ww  w .  ja  v  a  2  s. c om
            // FOR TCS adapter, we prefer the TEMPERATURE_TCS
            // FOR WLAB and HAI we prefer the TEMPERATURE_ALT
            // we do this check because the getMoteUriResource is making a reverse lookup in the hashmap (where two keys point to the same resource)
            if (theResourceName.compareToIgnoreCase(MoteResource.TEMPERATURE_TCS) == 0) {
                theResourceName = MoteResource.TEMPERATURE_ALT;
            }
            moteUriResource += theResourceName;
            int packetID = UNDEFINED_COAP_MESSAGE_ID;
            do { //while loop to avoid a packetID that exists in the array that is to be ignored!
                packetID = random.nextInt(65535) + 1;
            } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                    || packetID == UNDEFINED_COAP_MESSAGE_ID);

            String msgString = packetID + "#" + node.getId() + "#" + RESOURCE_REQ + "#" + moteUriResource;
            byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
            msgBytes = msgString.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                    InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
            DatagramSocket clientSocket = new DatagramSocket();
            clientSocket.send(sendPacket);
            clientSocket.close();
            requestMsgId = packetID;
            logger.info("Sent Request: " + msgString);
        } else {
            logger.warn("No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
            throw new WSIAdapterException(
                    "No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
        }
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}