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:org.lwes.emitter.UnicastEventEmitter.java

/**
 * @param bytes the byte array to emit//from w ww . j av  a2s  .  c  o  m
 * @param address the address to use
 * @param port the port to use
 * @throws IOException throws an IOException if there is a network error
 */
protected void emit(byte[] bytes, InetAddress address, int port) throws IOException {
    /* don't send null bytes */
    if (bytes == null)
        return;

    DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port);
    socket.send(dp);

    if (log.isTraceEnabled()) {
        log.trace("Sent to network '" + NumberCodec.byteArrayToHexString(dp.getData(), 0, dp.getLength()));
    }
}

From source file:sx.blah.discord.api.internal.UDPVoiceSocket.java

/**
 * Obtains the machine's external IP address and port to send to Discord.
 *
 * @param ssrc The self user's ssrc.//from www . j  av  a2  s.  c o m
 * @return A pair of the machine's external IP address and port.
 * @throws IOException Thrown by underlying UDP socket.
 *
 * @see <a href=https://discordapp.com/developers/docs/topics/voice-connections#ip-discovery>IP Discovery</a>
 */
private Pair<String, Integer> doIPDiscovery(int ssrc) throws IOException {
    byte[] data = ByteBuffer.allocate(70).putInt(ssrc).array();
    DatagramPacket discoveryPacket = new DatagramPacket(data, data.length, address);
    udpSocket.send(discoveryPacket);

    DatagramPacket responsePacket = new DatagramPacket(new byte[70], 70);
    udpSocket.receive(responsePacket);

    byte[] receivedData = responsePacket.getData();
    String ip = new String(Arrays.copyOfRange(receivedData, 4, 68)).trim();
    int port = ((((int) receivedData[69]) & 0x000000FF) << 8) | (((int) receivedData[68]) & 0x000000FF);

    return Pair.of(ip, port);
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.distributor.impl.DistributorWorkerImpl.java

private DatagramPacket toPacket(List<PositionUpdateMsg> positionUpdateMsgs, int positionUpdateMsgsByteCount) {
    assert (positionUpdateMsgs != null);
    assert (positionUpdateMsgs.size() > 0);
    assert (positionUpdateMsgsByteCount > 0);
    assert (positionUpdateMsgsByteCount <= this.packetMaxSize);

    DatagramPacket packet = new DatagramPacket(new byte[positionUpdateMsgsByteCount],
            positionUpdateMsgsByteCount);
    byte[] packetData = packet.getData();
    int packetDataIndex = 0;
    for (PositionUpdateMsg positionUpdateMsg : positionUpdateMsgs) {
        byte[] positionUpdateMsgData = positionUpdateMsg.getPositionUpdateMsg().getData();
        int positionUpdateMsgDataLength = positionUpdateMsgData.length;
        System.arraycopy(positionUpdateMsgData, 0, packetData, packetDataIndex, positionUpdateMsgDataLength);
        packetDataIndex += positionUpdateMsgDataLength;
    }//from  w w w  . j  av a  2  s  . c om

    return packet;
}

From source file:de.jaetzold.networking.SimpleServiceDiscovery.java

private HueBridge parseResponsePacket(DatagramPacket receivePacket) {
    Log.d("HUE", "parse resonse");
    HueBridge bridge = null;/*w w w  .j  a v  a  2  s  . c o  m*/
    String message = new String(receivePacket.getData());
    if (message.contains("/description.xml")) {
        //System.out.println("there is a description.xml, lets get it");
        InetAddress address = receivePacket.getAddress();
        bridge = new HueBridge(address, "xx26xxb3xx10xx0fxx5bxxabxx7bxx57");
    }
    return bridge;
}

From source file:org.lwes.emitter.DatagramSocketEventEmitter.java

/**
 * @param bytes the byte array to emit//w w w.j  a v a2s  .  c o  m
 * @param address the address to use
 * @param port the port to use
 * @throws IOException throws an IOException if there is a network error
 * @return number of bytes emitted
 */
protected int emit(byte[] bytes, InetAddress address, int port) throws IOException {
    /* don't send null bytes */
    if (bytes == null)
        return 0;

    if (socket == null || socket.isClosed()) {
        throw new IOException("Socket wasn't initialized or was closed.");
    }

    DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port);
    socket.send(dp);

    if (log.isTraceEnabled()) {
        log.trace("Sent to network '" + NumberCodec.byteArrayToHexString(dp.getData(), 0, dp.getLength()));
    }
    return bytes.length;
}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

@Test
public void testUdpEchoServer() throws IOException {
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(//from   w w  w . j av a2 s.com
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            .withConnectorFactory(UdpConnectorFactory.Builder.builder()
                    .withDatagramMessageHandlerFactory(new UdpServiceFactory()).build())
            .build();
    simpleNbServer.start();
    String message1 = "this is message1";
    String message2 = "this is message2";
    String message3 = "quit";
    try {
        DatagramSocket socket = new DatagramSocket();
        SocketAddress address = new InetSocketAddress("localhost", 1111);

        // message 1
        byte[] payload1 = message1.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet = new DatagramPacket(payload1, payload1.length, address);
        socket.send(packet);
        byte[] response = new byte[50];
        DatagramPacket responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        String messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals(message1, messageRead);

        // message2
        byte[] payload2 = message2.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet2 = new DatagramPacket(payload2, payload2.length, address);
        socket.send(packet2);
        responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals(message2, messageRead);

        // message3
        byte[] payload3 = message3.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet3 = new DatagramPacket(payload3, payload3.length, address);
        socket.send(packet3);
        responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals("goodbye", messageRead);

    } finally {
        simpleNbServer.shutdown();
    }
}

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>/*from ww w.jav a 2 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:org.avineas.fins.gw.Gateway.java

private void traceDatagram(String prefix, DatagramPacket packet) {
    if (!logger.isDebugEnabled())
        return;/* www  . j ava  2 s .  c  o  m*/
    StringBuffer buffer = new StringBuffer(prefix).append(":");
    byte[] data = packet.getData();
    int offset = packet.getOffset();
    for (int cnt = 0; cnt < packet.getLength(); cnt++) {
        int thisByte = data[cnt + offset] & 0xff;
        buffer.append(" ").append(Integer.toHexString(thisByte));
    }
    logger.debug(buffer.toString());
}

From source file:org.proto.led.network.WiFiControllerService.java

private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception {
    byte[] recvBuf = new byte[400];
    if (socket == null || socket.isClosed()) {
        socket = new DatagramSocket(port);
        socket.setSoTimeout(5000);/*from   ww w  . j a v a 2 s .  com*/
        socket.setBroadcast(true);
    }
    DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
    Log.i(TAG, "Waiting for UDP broadcast");
    socket.receive(packet);

    String senderIP = packet.getAddress().getHostAddress();
    parseMessage(recvBuf, senderIP);
    String message = new String(packet.getData()).trim();
    Log.i(TAG, "Got UDP broadcast from " + senderIP + ", message: " + message);

    socket.close();
}

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

@Override
public void run() {
    LOGGER.debug("Listening for any multicast packets.");
    String data = "";
    while (!isCanceled) {
        try {//from  www. j  a va  2  s  .  c o  m
            byte buf[] = new byte[1024];
            DatagramPacket pack = new DatagramPacket(buf, buf.length);
            socket.receive(pack);
            data = new String(pack.getData(), pack.getOffset(), pack.getLength());
            LOGGER.debug("Packet received with the following payload: {}.", data);
            Probe probe = JAXB.unmarshal(new StringReader(data), Probe.class);

            List<RespondTo> respondTo = probe.getRa().getRespondTo();

            boolean ignoreProbe = false;
            if (ignoreProbesList != null && !ignoreProbesList.isEmpty()) {
                for (String ignoreProbeString : ignoreProbesList) {
                    String updatedIgnoreString = expandRespondToAddress(ignoreProbeString);
                    // TODO cache the request ID and use that instead of the local hostname
                    if (StringUtils.equalsIgnoreCase(updatedIgnoreString, respondTo.get(0).getValue())) {
                        LOGGER.debug(
                                "Configuration is set to ignore probes that have a respondTo of '{}'. Incoming probe contains respondTo of '{}'. IGNORING PROBE.",
                                ignoreProbeString, respondTo.get(0).getValue());
                        ignoreProbe = true;
                    }
                }
            }
            if (!ignoreProbe) {
                List<String> contractIDs = probe.getScids().getServiceContractID();
                // TODO handle the different contractID
                // URI contractId = probe.getContractID();
                String probeId = probe.getId();
                String response = generateServiceResponse(probe.getRespondToPayloadType(), contractIDs,
                        probeId);

                if (StringUtils.isNotBlank(response)) {
                    LOGGER.debug("Returning back to {} with the following response:\n{}",
                            respondTo.get(0).getValue(), response);
                    sendResponse(respondTo.get(0).getValue(), response, probe.getRespondToPayloadType());
                } else {
                    LOGGER.debug(
                            "No services found that match the incoming contract IDs, not sending a response.");
                }
            }
        } catch (DataBindingException e) {
            LOGGER.warn("Issue parsing probe response: {}", data, e);
        } catch (SocketTimeoutException ste) {
            LOGGER.trace("Received timeout on socket, resetting socket to check for cancellation.");
        } catch (IOException ioe) {
            if (!isCanceled) {
                LOGGER.warn("Error while trying to receive a packet, shutting down listener", ioe);
            }
            break;
        }
    }
    if (isCanceled) {
        LOGGER.debug("Listener was canceled, not receiving any more multicast packets.");
    }

}