Example usage for java.net DatagramPacket getLength

List of usage examples for java.net DatagramPacket getLength

Introduction

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

Prototype

public synchronized int getLength() 

Source Link

Document

Returns the length of the data to be sent or the length of the data received.

Usage

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.impl.PacketHandlerImpl.java

@Override
@Transactional/*from w w w.j  av  a  2 s  .co m*/
public boolean processPacket(RelayServer relayServer, DatagramPacket packet) {
    try {
        this.txChecker.checkInTx("PacketHandler::processPacket");
    } catch (Throwable e) {
        e.printStackTrace();
    }

    long utcTimestamp = System.currentTimeMillis();
    boolean updated = false;

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("[" + utcTimestamp + "] Received " + packet.getLength() + " bytes from "
                + packet.getAddress().getHostAddress() + ":" + packet.getPort());
    }

    try {
        InetAddress srcIp = packet.getAddress();
        int srcPort = packet.getPort();

        /* get sender or create */
        Sender sender = this.senders.getSender(srcIp, srcPort);
        if (sender == null) {
            sender = new Sender(srcIp, Integer.valueOf(srcPort), relayServer);
        }

        /* make sure the sender is linked to this relayServer */
        sender.setRelayServer(relayServer);

        /* get packet data */
        byte[] packetData = packet.getData();
        int packetLength = packet.getLength();

        /* parse the uplink packet for messages */
        int messageOffset = 0;
        while (messageOffset < packetLength) {
            int messageType = UplinkMessage.getUplinkMessageType(packetData, messageOffset);
            int messageLength = UplinkMessage.getUplinkMessageHeaderLength()
                    + UplinkMessage.getUplinkMessageLength(packetData, messageOffset);

            if ((messageType != UplinkMessage.getUplinkMessageTypePosition())
                    && (messageType != UplinkMessage.getUplinkMessageTypeClusterLeader())) {
                this.logger.warn("Uplink message type " + messageType + " not supported: ignored");
            } else {
                byte[] messageData = Arrays.copyOfRange(packetData, messageOffset,
                        messageOffset + messageLength);
                DumpUtil.dumpUplinkMessage(this.logger, Level.DEBUG, messageData, srcIp, srcPort, messageType,
                        utcTimestamp, "  ");

                Object msg = null;
                boolean msgCausedUpdate = false;
                if (messageType == UplinkMessage.getUplinkMessageTypePosition()) {
                    msg = new PositionUpdate(messageData, messageLength);
                    msgCausedUpdate = this.positionUpdateHandler.handlePositionMessage(sender, utcTimestamp,
                            (PositionUpdate) msg);
                } else /* if (messageType == UplinkMessage.getUplinkMessageTypeClusterLeader()) */ {
                    msg = new ClusterLeader(messageData, messageLength);
                    msgCausedUpdate = this.clusterLeaderHandler.handleClusterLeaderMessage(sender, utcTimestamp,
                            (ClusterLeader) msg);
                }
                if (msgCausedUpdate && this.useFaker) {
                    this.faker.fakeit(sender, utcTimestamp, msg);
                }
                updated = msgCausedUpdate || updated;
            }

            messageOffset += messageLength;
        }

        return updated;
    } catch (Throwable e) {
        this.logger.error("error during packet handling", e);
        return updated;
    } finally {
        if (this.useFaker) {
            this.faker.setFirstFake(false);
        }
    }
}

From source file:cai.flow.collector.Collector.java

/**
 *
 * @param p//from   w ww.j a va  2 s .  c o  m
 */
private synchronized void processPacket(final DatagramPacket p) {
    final byte[] buf = p.getData();
    int len = p.getLength();
    String addr = p.getAddress().getHostAddress().trim();

    synchronized (data_queue) {
        processed++;
    }

    logger.debug(addr + "(" + p.getAddress().getHostName() + ") " + len + " bytes");
    try {
        if (len < 2)
            throw new DoneException("  * too short packet *");

        short version = (short) Util.to_number(buf, 0, 2);

        if (version > MAX_VERION || version <= 0)
            throw new DoneException("  * unsupported version *");

        if (!isVersionEnabled[version - 1])
            throw new DoneException("  * version " + version + " disabled *");

        logger.debug("  version: " + version);

        FlowPacket packet;

        switch (version) {
        case 1:
            packet = (FlowPacket) new V1_Packet(addr, buf, len);
            break;
        case 5:
            packet = (FlowPacket) new V5_Packet(addr, buf, len);
            break;
        // Temporarily removing NetFlow Version 7 until Resources fully removed
        /*
        case 7:
        packet = (FlowPacket) new V7_Packet(addr, resources, buf, len);
        break;
        */
        case 8:
            packet = (FlowPacket) new V8_Packet(addr, buf, len);
            break;
        case 9:
            packet = (FlowPacket) new V9_Packet(addr, buf, len);
            break;
        default:
            logger.error("Collector - Version problem.  Version = " + version);
            return;
        }
        aggregator.process(packet);
    } catch (DoneException e) {
        e.printStackTrace();
        logger.info(e);
    }
}

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

/**
 * Constructs a new event encapsulation instance based upon the
 * information passed to the method. The passed datagram data is decoded
 * into a string using the <tt>US-ASCII</tt> character encoding.
 *
 * @param packet The datagram received from the remote agent.
 * @throws java.io.UnsupportedEncodingException
 *          Thrown if the data buffer cannot be decoded using the
 *          US-ASCII encoding./* ww  w .j a v  a 2  s . c  om*/
 * @throws MessageDiscardedException 
 */
public ConvertToEvent(final DatagramPacket packet, final SyslogdConfig config)
        throws UnsupportedEncodingException, MessageDiscardedException {
    this(packet.getAddress(), packet.getPort(), new String(packet.getData(), 0, packet.getLength(), "US-ASCII"),
            config);
}

From source file:org.apache.jmeter.JMeter.java

private static void waitForSignals(final List<JMeterEngine> engines, DatagramSocket socket) {
    byte[] buf = new byte[80];
    System.out.println(//from   w w  w .  j av a  2 s .  c o  m
            "Waiting for possible Shutdown/StopTestNow/Heapdump message on port " + socket.getLocalPort());
    DatagramPacket request = new DatagramPacket(buf, buf.length);
    try {
        while (true) {
            socket.receive(request);
            InetAddress address = request.getAddress();
            // Only accept commands from the local host
            if (address.isLoopbackAddress()) {
                String command = new String(request.getData(), request.getOffset(), request.getLength(),
                        "ASCII");
                System.out.println("Command: " + command + " received from " + address);
                log.info("Command: " + command + " received from " + address);
                if (command.equals("StopTestNow")) {
                    for (JMeterEngine engine : engines) {
                        engine.stopTest(true);
                    }
                } else if (command.equals("Shutdown")) {
                    for (JMeterEngine engine : engines) {
                        engine.stopTest(false);
                    }
                } else if (command.equals("HeapDump")) {
                    HeapDumper.dumpHeap();
                } else {
                    System.out.println("Command: " + command + " not recognised ");
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        socket.close();
    }
}

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

public void run() {
    InetAddress group = null;// www.j av  a2  s  .co m
    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.ionicsdk.discovery.Discovery.java

public void doIdentify(final JSONObject opts, final CallbackContext callbackContext) {
    new AsyncTask<Integer, Void, Void>() {

        @Override//  www. ja v  a2  s  .  com
        protected Void doInBackground(Integer... params) {
            try {
                DatagramSocket socket = new DatagramSocket();
                socket.setBroadcast(true);

                String data = opts.toString();

                DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
                        getBroadcastAddress(), opts.getInt("port"));
                socket.send(packet);
                Log.d(TAG, "Sent packet");

                byte[] buf = new byte[1024];
                packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                String result = new String(buf, 0, packet.getLength());

                Log.d(TAG, "Got response packet of " + packet.getLength() + " bytes: " + result);

                callbackContext.success(result);

            } catch (Exception e) {
                callbackContext.error(e.getMessage());
                Log.e(TAG, "Exception while listening for server broadcast");
                e.printStackTrace();
            }
            return null;
        }
    }.execute();

}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPRequestPacket.java

/***
 * Creates a request packet of a given type based on a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>//ww  w  .ja  v  a2  s  .c  om
 * @param type The type of the request (either TFTPPacket.READ_REQUEST or
 *             TFTPPacket.WRITE_REQUEST).
 * @param datagram  The datagram containing the received request.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         request packet of the appropriate type.
 ***/
TFTPRequestPacket(int type, DatagramPacket datagram) throws TFTPPacketException {
    super(type, datagram.getAddress(), datagram.getPort());

    byte[] data;
    int index, length;
    String mode;
    StringBuffer buffer;

    data = datagram.getData();

    if (getType() != data[1])
        throw new TFTPPacketException("TFTP operator code does not match type.");

    buffer = new StringBuffer();

    index = 2;
    length = datagram.getLength();

    while (index < length && data[index] != 0) {
        buffer.append((char) data[index]);
        ++index;
    }

    _filename = buffer.toString();

    if (index >= length)
        throw new TFTPPacketException("Bad filename and mode format.");

    buffer.setLength(0);
    ++index; // need to advance beyond the end of string marker
    while (index < length && data[index] != 0) {
        buffer.append((char) data[index]);
        ++index;
    }

    mode = buffer.toString().toLowerCase();
    length = _modeStrings.length;

    for (index = 0; index < length; index++) {
        if (mode.equals(_modeStrings[index])) {
            _mode = index;
            break;
        }
    }

    if (index >= length) {
        throw new TFTPPacketException("Unrecognized TFTP transfer mode: " + mode);
        // May just want to default to binary mode instead of throwing
        // exception.
        //_mode = TFTP.OCTET_MODE;
    }
}

From source file:udpserver.UDPui.java

private void tempReceiveUDP() {
    background = new Runnable() {
        public void run() {
            try {
                serverSocket = new DatagramSocket(9876);
            } catch (SocketException ex) {
                Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
            }/*from   ww w .j  a  v  a  2  s .  c o  m*/
            //                while (true) {
            //                    byte[] receiveData = new byte[1024];
            //                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            //                    if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) {
            //                        int count = 1;
            while (true) {
                try {
                    byte[] receiveData = new byte[total_byte];
                    byte[] sendData = new byte[32];
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                    serverSocket.receive(receivePacket);
                    String message = new String(receivePacket.getData(), receivePacket.getOffset(),
                            receivePacket.getLength());
                    //                                String word = serverSocket.getInetAddress().toString();
                    //                                Integer count = counting.get(word);
                    //                                if (count == null) {
                    //                                    counting.put(word, 1);
                    //                                }
                    //                                else {
                    //                                    counting.put(word, count + 1);
                    //                                }

                    boolean looprun = true;
                    String word = receivePacket.getAddress().getHostAddress();
                    System.out.println(word);
                    //                        System.out.println(message);
                    while (looprun) {
                        if (message.contains("&")) {
                            message = message.substring(message.indexOf("&") + 1);
                            Integer count = counting.get(word);
                            if (count == null) {
                                counting.put(word, 2);
                            } else {
                                counting.put(word, count + 1);
                            }
                            //                                System.out.println(count + ":" + message);
                        } else {
                            looprun = false;
                        }
                    }

                    if (message.equals("end")) {
                        valuePane.setCaretPosition(valuePane.getDocument().getLength());
                        //send back to mobile
                        InetAddress IPAddress = receivePacket.getAddress();
                        int port = receivePacket.getPort();
                        String capitalizedSentence = counting.get(word) + "";
                        sendData = capitalizedSentence.getBytes();
                        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
                                port);
                        serverSocket.send(sendPacket);
                        //end send back to mobile
                        //                                    count = 1;
                        //                                    break;
                        counting.remove(word);
                    } else if (available) {

                        //                                    series.add(count, Double.parseDouble(message));
                        //                                    valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n");
                        //                                    valuePane.setCaretPosition(valuePane.getDocument().getLength());
                        //                                    count++;
                    }
                } catch (IOException ex) {
                    Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //                    }
            //                }
        }
    };
    backgroundProcess = new Thread(background);
}

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

/**
 * While running, repeatedly read datagrams and insert them into the queue along with the
 * receipt time and other metadata.//from  w w  w.jav  a 2 s  . co  m
 */
@Override
public void run() {
    running = true;

    while (running) {
        try {
            DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);
            socket.receive(datagram);
            if (log.isTraceEnabled()) {
                log.trace("Received datagram: " + datagram);
            }
            /* we record the time *after* the receive because it blocks */
            long receiptTime = System.currentTimeMillis();

            /* copy the data into a tight buffer so we can release the loose buffer */
            final byte[] tightBuffer = new byte[datagram.getLength()];
            System.arraycopy(datagram.getData(), 0, tightBuffer, 0, tightBuffer.length);
            datagram.setData(tightBuffer);

            /* create an element for the queue */
            DatagramQueueElement element = new DatagramQueueElement();
            element.setPacket(datagram);
            element.setTimestamp(receiptTime);

            /* add the element to the queue and notify everyone there's work to do */
            queue.put(element);
            if (log.isTraceEnabled()) {
                log.trace("Enqueued: " + element);
            }
        } catch (Exception e) {
            log.warn("Unable to read datagram", e);
        }
    }
}

From source file:org.openhab.binding.yeelight.internal.YeelightBinding.java

private void receiveData(MulticastSocket socket, DatagramPacket dgram) {

    try {/*from w ww .  ja v  a2s  .c  o  m*/
        while (true) {
            socket.receive(dgram);
            String sentence = new String(dgram.getData(), 0, dgram.getLength());

            logger.debug("Yeelight received packet: {}", sentence);

            if (isOKPacket(sentence) || isNotifyPacket(sentence)) {
                String[] lines = sentence.split("\n");
                String id = "";
                String location = "";
                String model = "";
                String support = "";
                for (String line : lines) {
                    line = line.replace("\r", "");
                    line = line.replace("\n", "");

                    if (line.startsWith("id: "))
                        id = line.substring(4);
                    else if (line.startsWith("Location: "))
                        location = line.substring(10);
                    else if (line.startsWith("model: "))
                        model = line.substring(7);
                    else if (line.startsWith("support: "))
                        support = line.substring(9);
                }
                if (!id.equals("") && !devices.containsKey(id)) {
                    YeelightDevice device = new YeelightDevice(id, location, model, support);
                    devices.put(id, device);
                    logger.info("Found Yeelight device :\n{}", device.toString());
                }
            }
        }
    } catch (IOException e) {
        logger.error(e.toString());
    }
}