Example usage for java.net DatagramPacket DatagramPacket

List of usage examples for java.net DatagramPacket DatagramPacket

Introduction

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

Prototype

public DatagramPacket(byte buf[], int length) 

Source Link

Document

Constructs a DatagramPacket for receiving packets of length length .

Usage

From source file:net.spfbl.dnsbl.QueryDNSBL.java

/**
 * Inicializao do servio./*from   ww w.ja  v a2  s . c  o  m*/
 */
@Override
public void run() {
    try {
        Server.logInfo("listening DNSBL on UDP port " + PORT + ".");
        while (continueListenning()) {
            try {
                byte[] receiveData = new byte[1024];
                DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
                SERVER_SOCKET.receive(packet);
                if (continueListenning()) {
                    long time = System.currentTimeMillis();
                    Connection connection = pollConnection();
                    if (connection == null) {
                        InetAddress ipAddress = packet.getAddress();
                        String result = "TOO MANY CONNECTIONS\n";
                        Server.logQueryDNSBL(time, ipAddress, null, result);
                    } else {
                        try {
                            connection.process(packet, time);
                        } catch (IllegalThreadStateException ex) {
                            // Houve problema na liberao do processo.
                            InetAddress ipAddress = packet.getAddress();
                            String result = "ERROR: FATAL\n";
                            Server.logError(ex);
                            Server.logQueryDNSBL(time, ipAddress, null, result);
                            offer(connection);
                        }
                    }
                }
            } catch (SocketException ex) {
                // Conexo fechada externamente pelo mtodo close().
            }
        }
    } catch (Exception ex) {
        Server.logError(ex);
    } finally {
        Server.logInfo("querie DNSBL server closed.");
    }
}

From source file:net.fenyo.mail4hotspot.dns.DnsListener.java

public void run() {
    final ExecutorService pool = Executors.newCachedThreadPool();

    try {/* ww  w. j a  v a  2 s . c o  m*/
        socket = new DatagramSocket(DNSPORT);
    } catch (final SocketException ex) {
        ex.printStackTrace();
        log.error("can not start DNS service");
        return;
    }

    do {
        final DatagramPacket query = new DatagramPacket(new byte[DATAGRAMMAXSIZE], DATAGRAMMAXSIZE);
        try {
            socket.receive(query);
            pool.execute(new Handler(query));
        } catch (IOException ex) {
            log.error(ex);
        }
    } while (thread.isInterrupted() == false);

    try {
        log.info("waiting for executor tasks to terminate");
        pool.awaitTermination(120, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        log.error(ex);
    }
}

From source file:net.spfbl.dns.QueryDNS.java

/**
 * Inicializao do servio.//from w ww .  j  a v a2  s . co m
 */
@Override
public void run() {
    try {
        Server.logInfo("listening DNS on UDP port " + PORT + ".");
        while (continueListenning()) {
            try {
                byte[] receiveData = new byte[1024];
                DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
                SERVER_SOCKET.receive(packet);
                if (continueListenning()) {
                    long time = System.currentTimeMillis();
                    Connection connection = pollConnection();
                    if (connection == null) {
                        InetAddress ipAddress = packet.getAddress();
                        String result = "TOO MANY CONNECTIONS\n";
                        Server.logQueryDNSBL(time, ipAddress, null, result);
                    } else {
                        try {
                            connection.process(packet, time);
                        } catch (IllegalThreadStateException ex) {
                            // Houve problema na liberao do processo.
                            InetAddress ipAddress = packet.getAddress();
                            String result = "ERROR: FATAL\n";
                            Server.logError(ex);
                            Server.logQueryDNSBL(time, ipAddress, null, result);
                            offer(connection);
                        }
                    }
                }
            } catch (SocketException ex) {
                // Conexo fechada externamente pelo mtodo close().
            }
        }
    } catch (Exception ex) {
        Server.logError(ex);
    } finally {
        Server.logInfo("querie DNS server closed.");
    }
}

From source file:com.mobiperf.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * //from w  ww .  j a  v  a 2 s .  c o  m
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port)
        throws IOException {

    long startTime = 0;
    long endTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[packetSize];
    long[] retval = { -1, -1 };
    long numLost = 0;
    int i = 0;
    long dataConsumedThisTask = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    // number * (packet sent + packet received)
    dataConsumedThisTask += num * (size + packetSize);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");
        for (i = 0; i < num; i++) {
            socket.send(packet);
        }
        for (i = 0; i < num; i++) {
            socket.receive(packetRcv);
            if (i == 0) {

                endTime = System.currentTimeMillis();
            }
        }
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out");
        numLost += (num - i);
        socket.close();
    }
    Logger.d("Sending complete: " + endTime);

    retval[0] = endTime - startTime;
    retval[1] = numLost;

    incrementData(dataConsumedThisTask);
    return retval;
}

From source file:com.mobiperf.measurements.RRCTask.java

/** 
 * Send a single packet of the size indicated and wait for a response.
 * /*w ww  .j ava2 s .  co m*/
 * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the
 * time from when the packet was sent to when a response was returned by the echo server.
 * 
 * @param serverAddr Echo server to calculate round trip
 * @param size size of packet to send in bytes
 * @param rcvSize size of packets sent from the echo server
 * @param port where the echo server is listening
 * @return The round trip time for the packet
 * @throws IOException
 */
public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException {
    long startTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[rcvSize];
    long dataConsumedThisTask = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);

    dataConsumedThisTask += (size + rcvSize);

    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");

        socket.send(packet);
        socket.receive(packetRcv);
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out, trying again");
        socket.close();
        return -1;
    }
    long endTime = System.currentTimeMillis();
    Logger.d("Sending complete: " + endTime);
    incrementData(dataConsumedThisTask);
    return endTime - startTime;
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * /*from  w w w .j a va 2  s.  c  o  m*/
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port)
        throws IOException {

    long startTime = 0;
    long endTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[packetSize];
    long[] retval = { -1, -1 };
    long numLost = 0;
    int i = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");
        for (i = 0; i < num; i++) {
            socket.send(packet);
        }
        for (i = 0; i < num; i++) {
            socket.receive(packetRcv);
            if (i == 0) {

                endTime = System.currentTimeMillis();
            }
        }
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out");
        numLost += (num - i);
        socket.close();
    }
    Logger.d("Sending complete: " + endTime);

    retval[0] = endTime - startTime;
    retval[1] = numLost;

    return retval;
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Send a single packet of the size indicated and wait for a response.
 * /*from www  .  ja  v  a2 s  . c  o  m*/
 * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the
 * time from when the packet was sent to when a response was returned by the echo server.
 * 
 * @param serverAddr Echo server to calculate round trip
 * @param size size of packet to send in bytes
 * @param rcvSize size of packets sent from the echo server
 * @param port where the echo server is listening
 * @return The round trip time for the packet
 * @throws IOException
 */
public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException {
    long startTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[rcvSize];

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);

    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");

        socket.send(packet);
        socket.receive(packetRcv);
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out, trying again");
        socket.close();
        return -1;
    }
    long endTime = System.currentTimeMillis();
    Logger.d("Sending complete: " + endTime);

    return endTime - startTime;
}

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  om
            "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:org.opendaylight.lispflowmapping.integrationtest.MappingServiceIntegrationTest.java

License:asdf

private void sendPacket(byte[] bytesToSend, int port) {
    try {/*from www  .  j  a  v a 2 s  . com*/
        DatagramPacket packet = new DatagramPacket(bytesToSend, bytesToSend.length);
        initPacketAddress(packet, port);
        LOG.trace("Sending packet to LispPlugin on socket, port {}", port);
        socket.send(packet);
    } catch (Throwable t) {
        fail();
    }
}