Example usage for java.net DatagramPacket getData

List of usage examples for java.net DatagramPacket getData

Introduction

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

Prototype

public synchronized byte[] getData() 

Source Link

Document

Returns the data buffer.

Usage

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Extracts the packet type ID from the given datagram packet.
 * /*from w w w  .  j  av  a2s .  c o  m*/
 * @param packet
 *        the packet to extract the type ID from
 * @return the extracted packet type ID or <code>-1</code> if the ID could not be extracted
 */
private static int getPacketTypeID(final DatagramPacket packet) {

    final byte[] data = packet.getData();

    if (data == null) {
        return -1;
    }

    if (packet.getLength() < (PACKET_TYPE_ID_OFFSET + 4)) {
        return -1;
    }

    return byteArrayToInteger(data, PACKET_TYPE_ID_OFFSET);
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Extracts the packet ID from the given packet.
 * //www.  j  ava2 s  .c om
 * @param packet
 *        the packet to extract the ID from
 * @return the extracted ID or <code>-1</code> if the ID could not be extracted
 */
private static int extractPacketID(final DatagramPacket packet) {

    final byte[] data = packet.getData();

    if (data == null) {
        return -1;
    }

    if (data.length < (PACKET_ID_OFFSET + 4)) {
        return -1;
    }

    return byteArrayToInteger(data, PACKET_ID_OFFSET);
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Extracts an {@link InetAddress} object from the given datagram packet. The datagram packet must be of the type
 * <code>TM_ADDRESS_REPLY_PACKET_ID</code>.
 * /*from   w w  w.j  a va 2 s.  c o  m*/
 * @param packet
 *        the packet to extract the address from
 * @return the extracted address or <code>null</code> if it could not be extracted
 */
private static InetAddress extractInetAddress(DatagramPacket packet) {

    final byte[] data = packet.getData();

    if (data == null) {
        return null;
    }

    if (packet.getLength() < PAYLOAD_OFFSET + 8) {
        return null;
    }

    final int len = byteArrayToInteger(data, PAYLOAD_OFFSET);

    final byte[] addr = new byte[len];
    System.arraycopy(data, PAYLOAD_OFFSET + 4, addr, 0, len);

    InetAddress inetAddress = null;

    try {
        inetAddress = InetAddress.getByAddress(addr);
    } catch (UnknownHostException e) {
        return null;
    }

    return inetAddress;
}

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 {/*from   w ww. ja  v  a 2  s. c om*/
        //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:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Extracts the datagram packet's magic number and checks it matches with the local magic number.
 * /*from   w  w  w.  j  a v  a  2  s .co  m*/
 * @param packet
 *        the packet to check
 * @param magicNumber
 *        the magic number identifying the discovery service
 * @return <code>true</code> if the packet carries the magic number expected by the local service, otherwise
 *         <code>false</code>
 */
private static boolean isPacketForUs(final DatagramPacket packet, final int magicNumber) {

    final byte[] data = packet.getData();

    if (data == null) {
        return false;
    }

    if (packet.getLength() < (MAGIC_NUMBER_OFFSET + 4)) {
        return false;
    }

    if (byteArrayToInteger(data, MAGIC_NUMBER_OFFSET) != magicNumber) {
        return false;
    }

    return true;
}

From source file:net.anidb.udp.UdpResponse.java

/**
 * Returns a instance of the class.//w ww . ja  v  a 2 s  .c om
 * @param packet The datagram packet.
 * @param charset The charset.
 * @return The instance.
 * @throws IllegalArgumentException If the datagram packet is
 * <code>null</code>.
 * @throws UdpConnectionException If the structure of datagram packet isn't
 * valid.
 * @throws UnsupportedEncodingException If the given charset isn't
 * supported.
 */
protected static UdpResponse getInstance(final DatagramPacket packet, final Charset charset)
        throws UdpConnectionException, UnsupportedEncodingException {

    ByteBuffer byteBuffer;
    String data, returnCodeStr, returnString;
    int returnCode;
    UdpResponse response;
    int index;
    String[] entries, dataFields;
    UdpResponseEntry entry;

    if (packet == null) {
        throw new IllegalArgumentException("Argument packet is null.");
    }
    if (packet.getLength() < 5) {
        throw new UdpConnectionException(
                "The packet length is less than " + "the minimum of 5 bytes: " + packet.getLength());
    }
    byteBuffer = ByteBuffer.allocate(packet.getLength());
    byteBuffer = (ByteBuffer) byteBuffer.put(packet.getData(), 0, packet.getLength()).flip();
    data = charset.decode(byteBuffer).toString();
    LOG.debug("received = [" + data + ']');
    if (data.length() < 5) {
        throw new UdpConnectionException(
                "The string length is less than " + "the minimum of 5 characters: " + data);
    }
    // First 3 chars = return code
    returnCodeStr = data.substring(0, 3);
    data = data.substring(4);
    try {
        returnCode = Integer.parseInt(returnCodeStr);
    } catch (NumberFormatException nfe) {
        throw new UdpConnectionException("Couldn't parse return code: " + returnCodeStr, nfe);
    }
    // Return string.
    index = data.indexOf('\n');
    if (index < 0) {
        returnString = data;
        data = "";
    } else {
        returnString = data.substring(0, index);
        data = data.substring(index + 1);
    }
    response = new UdpResponse(returnCode, returnString);
    // Entries?
    if (data.length() > 0) {
        entries = data.split("\\n", -1);
        for (int eIndex = 0; eIndex < entries.length; eIndex++) {
            if ((entries[eIndex].length() == 0) && (eIndex == entries.length - 1)) {
                break;
            }
            entry = new UdpResponseEntry();
            dataFields = entries[eIndex].split("\\|", -1);
            for (int dfIndex = 0; dfIndex < dataFields.length; dfIndex++) {
                entry.addDataField(new DataField(dataFields[dfIndex], charset));
            }
            response.entries.addElement(entry);
        }
        // MTU size problem.
        // TODO Implement a better solution for the MTU problem.
        if ((response.entries.size() > 0) && (packet.getLength() == 1400)) {
            /*
             * I assume if the packet length is equal to the MTU size, the
             * last entry is cut and must be removed.
             */
            index = response.entries.size() - 1;
            //            entry = response.entries.elementAt(index);
            //            data = entry.getMessageString();
            //            LOG.debug("last line = [" + data + ']');
            response.entries.removeElementAt(index);
        }
    }
    return response;
}

From source file:org.vesalainen.net.sntp.NtpV4Impl.java

public NtpV4Impl() {
    DatagramPacket datagramPacket = getDatagramPacket();
    buf = datagramPacket.getData(); // superclass buf is private
    setVersion(VERSION_4);// w ww .  j a v  a 2 s.  c  o  m
}

From source file:com.liferay.util.transport.MulticastDatagramHandler.java

public void process(DatagramPacket packet) {
    byte[] bytes = packet.getData();

    if (_gzipData) {
        try {//from   w  w w .  j  ava 2s  .  c om
            bytes = getUnzippedBytes(bytes);
        } catch (Exception e) {
            _log.error(e, e);
        }
    }

    if (_shortData) {
        byte[] temp = new byte[96];

        System.arraycopy(bytes, 0, temp, 0, 96);

        bytes = temp;
    }

    StringBundler sb = new StringBundler(4);

    sb.append("[");
    sb.append(packet.getSocketAddress());
    sb.append("] ");
    sb.append(new String(bytes));

    if (_log.isInfoEnabled()) {
        _log.info(sb);
    }
}

From source file:uk.co.propter.sleeponlan.SleepService.java

private boolean isSleepPacket(DatagramPacket packet) {
    byte[] data = packet.getData();
    return startsWithZeroBytes(data) && containsSixteenMacAddresses(data);
}

From source file:MainClass.java

public void run() {
    byte[] buffer = new byte[65507];
    while (true) {
        if (stopped)
            return;
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
        try {/*from  w w  w  .j a  v  a  2s .c o  m*/
            socket.receive(dp);
            String s = new String(dp.getData(), 0, dp.getLength());
            System.out.println(s);
            Thread.yield();
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
}