Java Code Examples for java.net.DatagramPacket#getData()

The following examples show how to use java.net.DatagramPacket#getData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
static Map<String, Map<String, String>> retrieveResponse() throws Exception {
    String response = null;
    Map<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();
    MulticastSocket recSocket = setUpSocket();

    int i = 0;
    logger.debug("Retrieving response");
    while (i < 10) {
        byte[] buf = new byte[2048];
        DatagramPacket input = new DatagramPacket(buf, buf.length);
        try {
            recSocket.receive(input);
            response = new String(input.getData());
            Map<String, String> parsedResponse = parseResponse(response);
            result.put(parsedResponse.get("IP"), parsedResponse);
        } catch (SocketTimeoutException e) {
            if (i >= 10) {
                break;
            }
            i++;
        }
    }
    logger.debug("Response retrieved: {}", result);
    return result;
}
 
Example 2
Source File: StatsDReporterTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	while (running) {
		try {
			byte[] buffer = new byte[1024];

			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

			socket.receive(packet);

			String line = new String(packet.getData(), 0, packet.getLength(), ConfigConstants.DEFAULT_CHARSET);

			lines.put(line, obj);

			synchronized (lines) {
				lines.notifyAll();
			}
		} catch (IOException ex) {
			// ignore the exceptions
		}
	}
}
 
Example 3
Source File: Socks5DatagramSocket.java    From T0rlib4Android with Apache License 2.0 6 votes vote down vote up
/**
 * This method allows to send datagram packets with address type DOMAINNAME.
 * SOCKS5 allows to specify host as names rather than ip addresses.Using
 * this method one can send udp datagrams through the proxy, without having
 * to know the ip address of the destination host.
 * <p>
 * If proxy specified for that socket has an option resolveAddrLocally set
 * to true host will be resolved, and the datagram will be send with address
 * type IPV4, if resolve fails, UnknownHostException is thrown.
 * 
 * @param dp
 *            Datagram to send, it should contain valid port and data
 * @param host
 *            Host name to which datagram should be send.
 * @throws IOException
 *             If error happens with I/O, or the host can't be resolved when
 *             proxy settings say that hosts should be resolved locally.
 * @see Socks5Proxy#resolveAddrLocally(boolean)
 */
public void send(DatagramPacket dp, String host) throws IOException {
	if (proxy.isDirect(host)) {
		dp.setAddress(InetAddress.getByName(host));
		super.send(dp);
		return;
	}

	if ((proxy).resolveAddrLocally) {
		dp.setAddress(InetAddress.getByName(host));
	}

	final byte[] head = formHeader(host, dp.getPort());
	byte[] buf = new byte[head.length + dp.getLength()];
	final byte[] data = dp.getData();
	// Merge head and data
	System.arraycopy(head, 0, buf, 0, head.length);
	// System.arraycopy(data,dp.getOffset(),buf,head.length,dp.getLength());
	System.arraycopy(data, 0, buf, head.length, dp.getLength());

	if (encapsulation != null) {
		buf = encapsulation.udpEncapsulate(buf, true);
	}

	super.send(new DatagramPacket(buf, buf.length, relayIP, relayPort));
}
 
Example 4
Source File: UDPServer.java    From cst with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Receives information from server as an array of bytes
 * @return
 */
public synchronized byte[] receiveByteArray(){
	byte[] receiveData = new byte[bufferSize];  //TODO Must be dynamic

	DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
	try {
		serverSocket.receive(receivePacket);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 

	//		String sentence = new String(receivePacket.getData()); 
	byte[] sentence = receivePacket.getData();
	return sentence;
}
 
Example 5
Source File: UdpMaster.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
private IpMessageResponse receiveImpl() throws IOException, ModbusTransportException {
    DatagramPacket packet = new DatagramPacket(new byte[MESSAGE_LENGTH], MESSAGE_LENGTH);
    socket.receive(packet);

    // We could verify that the packet was received from the same address to which the request was sent,
    // but let's not bother with that yet.

    ByteQueue queue = new ByteQueue(packet.getData(), 0, packet.getLength());
    IpMessageResponse response;
    try {
        response = (IpMessageResponse) messageParser.parseMessage(queue);
    }
    catch (Exception e) {
        throw new ModbusTransportException(e);
    }

    if (response == null)
        throw new ModbusTransportException("Invalid response received");

    return response;
}
 
Example 6
Source File: Socks5DatagramPacketHandler.java    From sockslib with Apache License 2.0 6 votes vote down vote up
@Override
public DatagramPacket encapsulate(DatagramPacket packet, SocketAddress destination) throws
    SocksException {
  if (destination instanceof InetSocketAddress) {
    InetSocketAddress destinationAddress = (InetSocketAddress) destination;
    final byte[] data = packet.getData();
    final InetAddress remoteServerAddress = packet.getAddress();
    final byte[] addressBytes = remoteServerAddress.getAddress();
    final int ADDRESS_LENGTH = remoteServerAddress.getAddress().length;
    final int remoteServerPort = packet.getPort();
    byte[] buffer = new byte[6 + packet.getLength() + ADDRESS_LENGTH];

    buffer[0] = buffer[1] = 0; // reserved byte
    buffer[2] = 0; // fragment byte
    buffer[3] = (byte) (ADDRESS_LENGTH == 4 ? AddressType.IPV4 : AddressType.IPV6);
    System.arraycopy(addressBytes, 0, buffer, 4, ADDRESS_LENGTH);
    buffer[4 + ADDRESS_LENGTH] = SocksUtil.getFirstByteFromInt(remoteServerPort);
    buffer[5 + ADDRESS_LENGTH] = SocksUtil.getSecondByteFromInt(remoteServerPort);
    System.arraycopy(data, 0, buffer, 6 + ADDRESS_LENGTH, packet.getLength());
    return new DatagramPacket(buffer, buffer.length, destinationAddress.getAddress(),
        destinationAddress.getPort());
  } else {
    throw new IllegalArgumentException("Only support java.net.InetSocketAddress");
  }
}
 
Example 7
Source File: StatsDReporterTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	while (running) {
		try {
			byte[] buffer = new byte[1024];

			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

			socket.receive(packet);

			String line = new String(packet.getData(), 0, packet.getLength(), ConfigConstants.DEFAULT_CHARSET);

			lines.put(line, obj);

			synchronized (lines) {
				lines.notifyAll();
			}
		} catch (IOException ex) {
			// ignore the exceptions
		}
	}
}
 
Example 8
Source File: NetworkGlueUDP.java    From TorrentEngine with GNU General Public License v3.0 5 votes vote down vote up
public boolean
packetReceived(
	DatagramPacket	packet )
{
	if ( packet.getLength() >= 12 ){
							
		byte[]	data = packet.getData();
		
			// first and third word must have something set in mask: 0xfffff800
		
		if ( 	(	( data[0] & 0xff ) != 0 ||
					( data[1] & 0xff ) != 0 ||
					( data[2] & 0xf8 ) != 0 ) &&
				
				(	( data[8] & 0xff ) != 0 ||
					( data[9] & 0xff ) != 0 ||
					( data[10]& 0xf8 ) != 0 )){
			
			total_packets_received++;
			total_bytes_received += packet.getLength();
			
			listener.receive( handler.getPort(), new InetSocketAddress( packet.getAddress(), packet.getPort()), packet.getData(), packet.getLength());
			
				// consume this packet 
			
			return( true );
		}
	}
	
		// don't consume it, allow it to be passed on for further processing
	
	return( false );
}
 
Example 9
Source File: PingMessage.java    From finalspeed-91yun with GNU General Public License v2.0 5 votes vote down vote up
public PingMessage(DatagramPacket dp){
	this.dp=dp;
	dpData=dp.getData();
	ver=ByteShortConvert.toShort(dpData, 0);
	sType=ByteShortConvert.toShort(dpData, 2);
	connectId=ByteIntConvert.toInt(dpData, 4);
	clientId=ByteIntConvert.toInt(dpData, 8);
	pingId=ByteIntConvert.toInt(dpData, 12);
	downloadSpeed=ByteShortConvert.toShort(dpData, 16);
	uploadSpeed=ByteShortConvert.toShort(dpData, 18);
}
 
Example 10
Source File: UDPTestServer.java    From sockslib with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  int port = 5050;
  if (args.length == 1) {
    port = Integer.parseInt(args[0]);
  }

  DatagramSocket server = new DatagramSocket(port);
  System.out.println("Listening port at:" + server.getLocalPort());
  byte[] receiveBuffer = new byte[1024];
  DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
  final String responseMsg = "Yes, I am UDP server";

  while (true) {
    server.receive(receivePacket);
    String msg = new String(receivePacket.getData(), 0, receivePacket.getLength());
    System.out.println("received message:" + msg);
    if (msg.equals("quit")) {
      break;
    }

    System.out.println("Response:" + responseMsg);
    byte[] data = responseMsg.getBytes();
    DatagramPacket packet =
        new DatagramPacket(data, data.length, receivePacket.getAddress(), receivePacket.getPort
            ());
    server.send(packet);
  }
  server.close();
}
 
Example 11
Source File: DataMessage.java    From finalspeed-91yun with GNU General Public License v2.0 5 votes vote down vote up
public DataMessage(DatagramPacket dp){
	this.dp=dp;
	dpData=dp.getData();
	ver=ByteShortConvert.toShort(dpData, 0);
	sType=ByteShortConvert.toShort(dpData, 2);
	
	connectId=ByteIntConvert.toInt(dpData, 4);
	clientId=ByteIntConvert.toInt(dpData, 8);
	
	sequence=ByteIntConvert.toInt(dpData, 12);
	length=ByteShortConvert.toShort(dpData, 16);
	timeId=ByteIntConvert.toInt(dpData, 18);
	data=new byte[length];
	System.arraycopy(dpData, 22, data, 0, length);
}
 
Example 12
Source File: PingMessage2.java    From finalspeed-91yun with GNU General Public License v2.0 5 votes vote down vote up
public PingMessage2(DatagramPacket dp){
	this.dp=dp;
	dpData=dp.getData();
	ver=ByteShortConvert.toShort(dpData, 0);
	sType=ByteShortConvert.toShort(dpData, 2);
	connectId=ByteIntConvert.toInt(dpData, 4);
	clientId=ByteIntConvert.toInt(dpData, 8);
	pingId=ByteIntConvert.toInt(dpData, 12);
}
 
Example 13
Source File: SP2Device.java    From broadlink-java-api with MIT License 5 votes vote down vote up
public boolean getState() throws Exception {
    DatagramPacket packet = sendCmdPkt(new CmdPayload() {

        @Override
        public byte getCommand() {
            return 0x6a;
        }

        @Override
        public Payload getPayload() {
            return new Payload() {

                @Override
                public byte[] getData() {
                    byte[] b = new byte[16];
                    b[0] = 1;
                    return b;
                }

            };
        }

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

    log.debug("SP2 get state received encrypted bytes: " + DatatypeConverter.printHexBinary(data));

    int err = data[0x22] | (data[0x23] << 8);

    if (err == 0) {
        byte[] pl = decryptFromDeviceMessage(data);
        log.debug("SP2 get state  received bytes (decrypted): " + DatatypeConverter.printHexBinary(pl));
        return pl[0x4] == 1 ? true : false;
    } else {
        log.warn("SP2 get state received an error: " + Integer.toHexString(err) + " / " + err);
    }

    return false;
}
 
Example 14
Source File: EKeyPacketReceiver.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void run() {
    running = true; // start loop
    if (socket == null) {
        throw new IllegalStateException(
                "Cannot access socket. You must call" + " call initializeListener(..) first!");
    }

    byte[] lastpacket = null;
    DatagramPacket packet = new DatagramPacket(new byte[buffersize], buffersize);

    while (running) {

        ekeypacket = null;
        packet.setData(new byte[buffersize]);

        try { // wait for the packet
            socket.receive(packet);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        // ignore packets from destinations other than the specified address
        // if destIp is not set ignore address check - this is not recommended but valid
        if (destIp == null || packet.getAddress().equals(destIp)) {

            lastpacket = packet.getData();

            try { // catch a possible parsing error

                switch (mode) {
                    case UniformPacket.tHOME:
                        ekeypacket = new HomePacket(deliminator, lastpacket);
                        break;
                    case UniformPacket.tMULTI:
                        ekeypacket = new MultiPacket(deliminator, lastpacket);
                        break;
                    default: // default configuration is the rare packet
                        ekeypacket = new RarePacket(lastpacket);
                        break;

                }
            } catch (IllegalArgumentException e) {
                log.error("Error parsing packet", e);
            }
        }

        if (ekeypacket != null) {
            listener.publishUpdate(ekeypacket);
        } else {
            log.debug("Received a packet that does not match the mode\n" + "you specified in the 'openhab.cfg'!");
        }

    }

    log.debug("eKey Listener stopped!");

}
 
Example 15
Source File: DnsClient.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Tries to retreive an UDP packet matching the given xid
 * received within the timeout.
 * If a packet with different xid is received, the received packet
 * is enqueued with the corresponding xid in 'resps'.
 */
private byte[] doUdpQuery(Packet pkt, InetAddress server,
                                 int port, int retry, int xid)
        throws IOException, NamingException {

    int minTimeout = 50; // msec after which there are no retries.

    synchronized (udpSocket) {
        DatagramPacket opkt = new DatagramPacket(
                pkt.getData(), pkt.length(), server, port);
        DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
        // Packets may only be sent to or received from this server address
        udpSocket.connect(server, port);
        int pktTimeout = (timeout * (1 << retry));
        try {
            udpSocket.send(opkt);

            // timeout remaining after successive 'receive()'
            int timeoutLeft = pktTimeout;
            int cnt = 0;
            do {
                if (debug) {
                   cnt++;
                    dprint("Trying RECEIVE(" +
                            cnt + ") retry(" + (retry + 1) +
                            ") for:" + xid  + "    sock-timeout:" +
                            timeoutLeft + " ms.");
                }
                udpSocket.setSoTimeout(timeoutLeft);
                long start = System.currentTimeMillis();
                udpSocket.receive(ipkt);
                long end = System.currentTimeMillis();

                byte[] data = new byte[ipkt.getLength()];
                data = ipkt.getData();
                if (isMatchResponse(data, xid)) {
                    return data;
                }
                timeoutLeft = pktTimeout - ((int) (end - start));
            } while (timeoutLeft > minTimeout);

        } finally {
            udpSocket.disconnect();
        }
        return null; // no matching packet received within the timeout
    }
}
 
Example 16
Source File: DnsClient.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Tries to retreive an UDP packet matching the given xid
 * received within the timeout.
 * If a packet with different xid is received, the received packet
 * is enqueued with the corresponding xid in 'resps'.
 */
private byte[] doUdpQuery(Packet pkt, InetAddress server,
                                 int port, int retry, int xid)
        throws IOException, NamingException {

    int minTimeout = 50; // msec after which there are no retries.

    synchronized (udpSocketLock) {
        try (DatagramSocket udpSocket = getDatagramSocket()) {
            DatagramPacket opkt = new DatagramPacket(
                    pkt.getData(), pkt.length(), server, port);
            DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
            // Packets may only be sent to or received from this server address
            udpSocket.connect(server, port);
            int pktTimeout = (timeout * (1 << retry));
            try {
                udpSocket.send(opkt);

                // timeout remaining after successive 'receive()'
                int timeoutLeft = pktTimeout;
                int cnt = 0;
                do {
                    if (debug) {
                       cnt++;
                        dprint("Trying RECEIVE(" +
                                cnt + ") retry(" + (retry + 1) +
                                ") for:" + xid  + "    sock-timeout:" +
                                timeoutLeft + " ms.");
                    }
                    udpSocket.setSoTimeout(timeoutLeft);
                    long start = System.currentTimeMillis();
                    udpSocket.receive(ipkt);
                    long end = System.currentTimeMillis();

                    byte[] data = ipkt.getData();
                    if (isMatchResponse(data, xid)) {
                        return data;
                    }
                    timeoutLeft = pktTimeout - ((int) (end - start));
                } while (timeoutLeft > minTimeout);

            } finally {
                udpSocket.disconnect();
            }
            return null; // no matching packet received within the timeout
        }
    }
}
 
Example 17
Source File: UDPBurstTask.java    From Mobilyzer with Apache License 2.0 4 votes vote down vote up
/**
 * Receives a burst from the remote server and counts the number of packets that were received.
 * 
 * @param sock the datagram socket that can be used to receive the server's burst
 * 
 * @return the number of packets received from the server
 * @throws MeasurementError if an error occurs
 */
private UDPResult recvDownResponse(DatagramSocket sock) throws MeasurementError {
  int pktRecv = 0;
  UDPBurstDesc desc = (UDPBurstDesc) measurementDesc;

  // Receive response
  Logger.i("Waiting for UDP burst from " + desc.target);
  // Reconstruct UDP packet from flattened network data
  byte buffer[] = new byte[desc.packetSizeByte];
  DatagramPacket recvpacket = new DatagramPacket(buffer, buffer.length);
  MetricCalculator metricCalculator = new MetricCalculator(desc.udpBurstCount);
  for (int i = 0; i < desc.udpBurstCount; i++) {
    if (stopFlag) {
      throw new MeasurementError("Cancelled");
    }
    try {
      sock.setSoTimeout(RCV_DOWN_TIMEOUT);
      sock.receive(recvpacket);
    } catch (IOException e) {
      Logger.e("Timeout at round " + i);
      break;
    }

    UDPPacket dataPacket = new UDPPacket(recvpacket.getData());
    dataConsumed+=recvpacket.getLength();
    if (dataPacket.type == UDPBurstTask.PKT_DATA) {
      // Received seq number must be same with client seq
      if (dataPacket.seq != seq) {
        String err =
            "Server send data packets with different seq, old " + seq + " => new "
                + dataPacket.seq;
        Logger.e(err);
        throw new MeasurementError(err);
      }

      Logger.i("Recv UDP response from " + desc.target + " type:" + dataPacket.type + " burst:"
          + dataPacket.burstCount + " pktnum:" + dataPacket.packetNum + " timestamp:"
          + dataPacket.timestamp);

      pktRecv++;
      metricCalculator.addPacket(dataPacket.packetNum, dataPacket.timestamp);
    } else {
      throw new MeasurementError("Error closing input stream from " + desc.target);
    }
  } // for()

  UDPResult udpResult = new UDPResult();
  udpResult.packetCount = pktRecv;
  udpResult.outOfOrderRatio = metricCalculator.calculateOutOfOrderRatio();
  udpResult.jitter = metricCalculator.calculateJitter();
  return udpResult;
}
 
Example 18
Source File: DnsClient.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Tries to retreive an UDP packet matching the given xid
 * received within the timeout.
 * If a packet with different xid is received, the received packet
 * is enqueued with the corresponding xid in 'resps'.
 */
private byte[] doUdpQuery(Packet pkt, InetAddress server,
                                 int port, int retry, int xid)
        throws IOException, NamingException {

    int minTimeout = 50; // msec after which there are no retries.

    synchronized (udpSocket) {
        DatagramPacket opkt = new DatagramPacket(
                pkt.getData(), pkt.length(), server, port);
        DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
        // Packets may only be sent to or received from this server address
        udpSocket.connect(server, port);
        int pktTimeout = (timeout * (1 << retry));
        try {
            udpSocket.send(opkt);

            // timeout remaining after successive 'receive()'
            int timeoutLeft = pktTimeout;
            int cnt = 0;
            do {
                if (debug) {
                   cnt++;
                    dprint("Trying RECEIVE(" +
                            cnt + ") retry(" + (retry + 1) +
                            ") for:" + xid  + "    sock-timeout:" +
                            timeoutLeft + " ms.");
                }
                udpSocket.setSoTimeout(timeoutLeft);
                long start = System.currentTimeMillis();
                udpSocket.receive(ipkt);
                long end = System.currentTimeMillis();

                byte[] data = new byte[ipkt.getLength()];
                data = ipkt.getData();
                if (isMatchResponse(data, xid)) {
                    return data;
                }
                timeoutLeft = pktTimeout - ((int) (end - start));
            } while (timeoutLeft > minTimeout);

        } finally {
            udpSocket.disconnect();
        }
        return null; // no matching packet received within the timeout
    }
}
 
Example 19
Source File: DnsClient.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Tries to retrieve a UDP packet matching the given xid
 * received within the timeout.
 * If a packet with different xid is received, the received packet
 * is enqueued with the corresponding xid in 'resps'.
 */
private byte[] doUdpQuery(Packet pkt, InetAddress server,
                                 int port, int retry, int xid)
        throws IOException, NamingException {

    int minTimeout = 50; // msec after which there are no retries.

    synchronized (udpSocket) {
        DatagramPacket opkt = new DatagramPacket(
                pkt.getData(), pkt.length(), server, port);
        DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
        // Packets may only be sent to or received from this server address
        udpSocket.connect(server, port);
        int pktTimeout = (timeout * (1 << retry));
        try {
            udpSocket.send(opkt);

            // timeout remaining after successive 'receive()'
            int timeoutLeft = pktTimeout;
            int cnt = 0;
            do {
                if (debug) {
                   cnt++;
                    dprint("Trying RECEIVE(" +
                            cnt + ") retry(" + (retry + 1) +
                            ") for:" + xid  + "    sock-timeout:" +
                            timeoutLeft + " ms.");
                }
                udpSocket.setSoTimeout(timeoutLeft);
                long start = System.currentTimeMillis();
                udpSocket.receive(ipkt);
                long end = System.currentTimeMillis();

                byte[] data = ipkt.getData();
                if (isMatchResponse(data, xid)) {
                    return data;
                }
                timeoutLeft = pktTimeout - ((int) (end - start));
            } while (timeoutLeft > minTimeout);

        } finally {
            udpSocket.disconnect();
        }
        return null; // no matching packet received within the timeout
    }
}
 
Example 20
Source File: UdpSource.java    From Azzet with Open Software License 3.0 2 votes vote down vote up
/**
 * Parses the request from the given DatagramPacket.
 * 
 * @param packet
 *        The packet to parse the request from.
 * @return The request contained in the packet.
 */
public static String getRequest( DatagramPacket packet )
{
	return new String( packet.getData(), 0, packet.getLength() );
}