Example usage for java.net DatagramPacket getAddress

List of usage examples for java.net DatagramPacket getAddress

Introduction

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

Prototype

public synchronized InetAddress getAddress() 

Source Link

Document

Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.

Usage

From source file:poisondog.net.udp.DatagramMission.java

public DatagramResponse execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket(null);
    socket.setReuseAddress(true);/*www .  j a v a  2 s  .  c  om*/

    socket.setBroadcast(parameter.getBroadcast());
    if (parameter.getTimeout() > 0)
        socket.setSoTimeout(parameter.getTimeout());
    String data = IOUtils.toString(parameter.getInputStream());
    DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length());
    packet.setAddress(InetAddress.getByName(parameter.getHost()));
    packet.setPort(parameter.getPort());
    socket.send(packet);

    DatagramResponse response = new DatagramResponse(parameter.getResponseLength());
    DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length);
    socket.receive(responsePacket);
    response.setAddress(responsePacket.getAddress().getHostAddress());
    response.setPacketLength(responsePacket.getLength());
    socket.close();
    return response;
}

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

/***
 * Creates an acknowledgement packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>/*from w w  w .  j av  a2  s .  c o  m*/
 * @param datagram  The datagram containing the received acknowledgement.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         acknowledgement packet.
 ***/
TFTPAckPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.ACKNOWLEDGEMENT, datagram.getAddress(), datagram.getPort());
    byte[] data;

    data = datagram.getData();

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

    _blockNumber = (((data[2] & 0xff) << 8) | (data[3] & 0xff));
}

From source file:org.libreoffice.impressremote.communication.TcpServersFinder.java

private Server buildServer(DatagramPacket aSearchResultPacket, String aServerHostname) {
    String aServerAddress = aSearchResultPacket.getAddress().getHostAddress();

    return Server.newTcpInstance(aServerAddress, aServerHostname);
}

From source file:ch.aschaefer.udp.DatagramSocketToControlMessageConverter.java

@Override
public ControlMessage convert(DatagramPacket source) {
    return new ControlMessage().timestamp(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now()))
            .hex(toHex(source.getData())).source(source.getSocketAddress().toString())
            .targetHost(source.getAddress().getHostAddress()).targetPort(source.getPort());
}

From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java

/**
 * Checks whether a packet does contain all given keywords case insensitive.
 * If all keywords are contained the IP address of the packet sender will be
 * returned./*  w  ww  .  ja  va  2  s .  c  o  m*/
 * 
 * @param packet
 *            The data packet to be analyzed.
 * @param keywords
 *            The keywords to be searched for.
 * @return The IP of the sender if all keywords have been found, null
 *         otherwise.
 * 
 * @throws IOException
 */
private String analyzePacket(DatagramPacket packet, String... keywords) throws IOException {

    logger.debug("Analyzing answer message.");

    InetAddress addr = packet.getAddress();
    ByteArrayInputStream in = new ByteArrayInputStream(packet.getData(), 0, packet.getLength());
    String response = IOUtils.toString(in);

    boolean foundAllKeywords = true;

    for (String keyword : keywords) {
        foundAllKeywords &= response.toUpperCase().contains(keyword.toUpperCase());
    }

    if (foundAllKeywords) {
        logger.debug("Found matching answer.");
        return addr.getHostAddress();
    }

    logger.debug("Answer did not match.");
    return null;
}

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

/***
 * Creates an error packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>// w  w  w .jav a  2 s .c  om
 * @param datagram  The datagram containing the received error.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         error packet.
 ***/
TFTPErrorPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.ERROR, datagram.getAddress(), datagram.getPort());
    int index, length;
    byte[] data;
    StringBuffer buffer;

    data = datagram.getData();
    length = datagram.getLength();

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

    _error = (((data[2] & 0xff) << 8) | (data[3] & 0xff));

    if (length < 5)
        throw new TFTPPacketException("Bad error packet. No message.");

    index = 4;
    buffer = new StringBuffer();

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

    _message = buffer.toString();
}

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

/***
 * Creates a data packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>/*from  w  w  w.j  a va 2s  . c o  m*/
 * @param datagram  The datagram containing the received data.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         data packet.
 ***/
TFTPDataPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.DATA, datagram.getAddress(), datagram.getPort());

    _data = datagram.getData();
    _offset = 4;

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

    _blockNumber = (((_data[2] & 0xff) << 8) | (_data[3] & 0xff));

    _length = datagram.getLength() - 4;

    if (_length > MAX_DATA_LENGTH)
        _length = MAX_DATA_LENGTH;
}

From source file:com.springrts.springls.nat.NatHelpServer.java

/**
 * check UDP server for any new packets//w  w w.  j  a v  a 2s  .com
 */
private void checkForNewPackets() {

    DatagramPacket packet;
    while ((packet = fetchNextPackage()) != null) {
        InetAddress address = packet.getAddress();
        int clientPort = packet.getPort();
        String data = new String(packet.getData(), packet.getOffset(), packet.getLength());
        LOG.trace("*** UDP packet received from {} from port {}", address.getHostAddress(), clientPort);
        Client client = getContext().getClients().getClient(data);
        if (client == null) {
            continue;
        }
        client.setUdpSourcePort(clientPort);
        client.sendLine(String.format("UDPSOURCEPORT %d", clientPort));
    }
}

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   w w  w  . ja v a 2 s  .co  m*/
 * @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.lwes.listener.DatagramDequeuer.java

protected void handleElement(DatagramQueueElement element) {
    if (element == null) {
        return;//from   w  w  w.j  av  a2  s  .  c o  m
    }

    DatagramPacket packet = element.getPacket();
    if (packet == null) {
        return;
    }

    /* get some metadata */
    long timestamp = element.getTimestamp();
    IPAddress address = new IPAddress(packet.getAddress());
    int port = packet.getPort();

    /* now try to deserialize the packet */
    try {
        /* don't validate the event for now to save time */
        Event event = factory.createEvent(packet.getData(), false);
        event.setInt64(Event.RECEIPT_TIME, timestamp);
        event.setIPAddress(Event.SENDER_IP, address);
        event.setUInt16(Event.SENDER_PORT, port);
        if (log.isTraceEnabled()) {
            log.trace("Dispatching event " + event.toString());
        }
        dispatchEvent(event);
    } catch (Exception e) {
        if (log.isWarnEnabled()) {
            log.warn("Unable to deserialize event in handleElement()", e);
        }
    }
}