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, SocketAddress address) 

Source Link

Document

Constructs a datagram packet for sending packets of length length to the specified port number on the specified host.

Usage

From source file:yatftps.Yatftps.java

/**
 * main method listen to 69 port UDP.//from w  w w .java  2  s. c  o m
 * After receiving connection creates new thread for processing request.
 * @param args the command line arguments
 */
//public static void main(String[] args) {
@Override
public void init(DaemonContext daemonContext) throws DaemonInitException, Exception {

    String[] args = daemonContext.getArguments();
    LogWriter.readConfig();
    log = LogWriter.getLogger();
    Config cfg;

    /*
    * Accordingly RFC 1350 the data field is from zero to 512 bytes long. https://tools.ietf.org/html/rfc1350
    * Respectively  (Data Field) + (Block Field) + (Opcode Field) = 512 + 2 + 2 = 516 bytes
    */
    datagramLength = 516;
    /*
    * Reading config file and getting application settings
    */
    cfg = Config.getConfig();
    /*
    * Checking for start arguments
    */
    if (args.length >= 1) {
        for (String s : args) {
            switch (s) {
            case "--debug":
                LogWriter.setDebug(true);
                break;
            case "--check-config":
                Config.checkConfig();
                System.exit(0);
            }
        }
    }

    yatftpsThread = new Thread() {

        @Override
        public synchronized void start() {
            Yatftps.this.stopped = false;
            super.start();
        }

        @Override
        public void run() {
            while (!stopped) {

                log.info("Server started");

                // trying to listen port 69
                try (DatagramSocket socket = new DatagramSocket(69)) {

                    // receive first packet from client
                    DatagramPacket datapacket = new DatagramPacket(new byte[datagramLength], 0, datagramLength);
                    socket.receive(datapacket);

                    // create new thread for handling TFTP request
                    TftpHandler tftphandler = new TftpHandler(socket, datapacket);
                    Thread thread = new Thread(tftphandler);

                    thread.setDaemon(true);
                    thread.start();

                } catch (SocketException e) {
                    log.severe(
                            "SocketException: socket could not be opened, or the socket could not bind to the specified local port.  "
                                    + e);
                    log.info("Exiting");
                    System.exit(1);
                } catch (SecurityException e) {
                    log.severe(
                            "SecurityException: security manager exists and its checkListen method doesn't allow the operation "
                                    + e);
                    log.info("Exiting");
                    System.exit(1);
                } catch (IOException e) {
                    log.info("I/O error occurs" + e);
                }
            }
        }
    };
}

From source file:org.cloudata.core.common.metrics.GangliaContext31.java

protected void emitMetric(String name, String type, String value) throws IOException {
    if (name == null) {
        LOG.warn("Metric was emitted with no name.");
        return;//from  ww w  . j a  v a  2 s. co  m
    } else if (value == null) {
        LOG.warn("Metric name " + name + " was emitted with a null value.");
    } else if (type == null) {
        LOG.warn("Metric name " + name + ", value " + value + " has no type.");
    }

    LOG.debug("Emitting metric " + name + ", type " + type + ", value " + value + " from " + hostName);

    String units = getUnits(name);
    if (units == null) {
        LOG.warn("Metric name " + name + ", value " + value + " had 'null' units");
        units = "";
    }
    int slope = getSlope(name);
    int tmax = getTmax(name);
    int dmax = getDmax(name);
    offset = 0;
    String groupName = name.substring(0, name.lastIndexOf("."));

    // The following XDR recipe was done through a careful reading of
    // gm_protocol.x in Ganglia 3.1 and carefully examining the output of
    // the gmetric utility with strace.

    // First we send out a metadata message
    xdr_int(128); // metric_id = metadata_msg
    xdr_string(hostName); // hostname
    xdr_string(name); // metric name
    xdr_int(0); // spoof = False
    xdr_string(type); // metric type
    xdr_string(name); // metric name
    xdr_string(units); // units
    xdr_int(slope); // slope
    xdr_int(tmax); // tmax, the maximum time between metrics
    xdr_int(dmax); // dmax, the maximum data value

    xdr_int(1); /*Num of the entries in extra_value field for 
                  Ganglia 3.1.x*/
    xdr_string("GROUP"); /*Group attribute*/
    xdr_string(groupName); /*Group value*/

    for (SocketAddress socketAddress : metricsServers) {
        DatagramPacket packet = new DatagramPacket(buffer, offset, socketAddress);
        datagramSocket.send(packet);
    }

    // Now we send out a message with the actual value.
    // Technically, we only need to send out the metadata message once for
    // each metric, but I don't want to have to record which metrics we did and
    // did not send.
    offset = 0;
    xdr_int(133); // we are sending a string value
    xdr_string(hostName); // hostName
    xdr_string(name); // metric name
    xdr_int(0); // spoof = False
    xdr_string("%s"); // format field
    xdr_string(value); // metric value

    for (SocketAddress socketAddress : metricsServers) {
        DatagramPacket packet = new DatagramPacket(buffer, offset, socketAddress);
        datagramSocket.send(packet);
    }
}

From source file:com.bitbreeds.webrtc.dtls.DtlsMuxStunTransport.java

public void send(byte[] buf, int off, int len) throws IOException {
    if (len > getSendLimit()) {
        throw new TlsFatalAlert(AlertDescription.record_overflow);
    }//from  www .j a  v a  2s. c o m
    DatagramPacket packet = new DatagramPacket(buf, off, len);
    socket.send(packet);
}

From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

@Test
public void sendSocketBufferSize() throws IOException {
    DatagramPacket datagramPacket = new DatagramPacket(new byte[0], 0, 0);

    DatagramSocket datagramSocket = new DatagramSocket();
    datagramSocket.connect(new InetSocketAddress(ADDRESS, PORT));

    datagramSocket.send(datagramPacket);
    datagramSocket.close();/*from   w w  w .j  ava 2  s . co m*/
}

From source file:uk.me.sa.lightswitch.android.net.RequestMessage.java

private void sendMessageTo(byte[] message, String node) throws RemoteMessageException {
    try {/*from   w  w w.ja v  a2s. c o  m*/
        DatagramSocket s = new DatagramSocket();

        try {
            InetAddress[] addresses = InetAddress.getAllByName(node);
            List<IOException> failed = new ArrayList<IOException>(addresses.length);

            for (InetAddress address : addresses) {
                log.trace("Sending {} bytes to {}", message.length, address);

                try {
                    s.send(new DatagramPacket(message, message.length,
                            new InetSocketAddress(address, SERVICE)));
                } catch (IOException e) {
                    log.warn("Error sending datagram packet", e);
                    failed.add(e);
                }
            }

            if (addresses.length == 0) {
                log.error("No hosts to send to");
                throw new RemoteMessageException(new IllegalArgumentException("No hosts to send to"));
            } else if (failed.size() == addresses.length) {
                log.error("Error sending all datagram packets");
                throw new RemoteMessageException(failed.get(0));
            } else if (!failed.isEmpty()) {
                log.error("Error sending some (but not all) datagram packets");
            }
        } catch (UnknownHostException e) {
            log.error("Error resolving hostname", e);
            throw new RemoteMessageException(e);
        } catch (RuntimeException e) {
            log.error("Error sending request message", e);
            throw new RemoteMessageException(e);
        } finally {
            s.close();
        }
    } catch (SocketException e) {
        log.error("Error creating socket", e);
        throw new RemoteMessageException(e);
    }
}

From source file:org.apache.hadoop.metrics.ganglia.GangliaContext31.java

protected void emitMetric(String name, String type, String value) throws IOException {
    if (name == null) {
        LOG.warn("Metric was emitted with no name.");
        return;/*from  ww  w.j av  a  2s .c  o  m*/
    } else if (value == null) {
        LOG.warn("Metric name " + name + " was emitted with a null value.");
        return;
    } else if (type == null) {
        LOG.warn("Metric name " + name + ", value " + value + " has no type.");
        return;
    }

    LOG.debug("Emitting metric " + name + ", type " + type + ", value " + value + " from hostname" + hostName);

    String units = getUnits(name);
    if (units == null) {
        LOG.warn("Metric name " + name + ", value " + value + " had 'null' units");
        units = "";
    }
    int slope = getSlope(name);
    int tmax = getTmax(name);
    int dmax = getDmax(name);
    offset = 0;
    String groupName = name.substring(0, name.lastIndexOf("."));

    // The following XDR recipe was done through a careful reading of
    // gm_protocol.x in Ganglia 3.1 and carefully examining the output of
    // the gmetric utility with strace.

    // First we send out a metadata message
    xdr_int(128); // metric_id = metadata_msg
    xdr_string(hostName); // hostname
    xdr_string(name); // metric name
    xdr_int(0); // spoof = False
    xdr_string(type); // metric type
    xdr_string(name); // metric name
    xdr_string(units); // units
    xdr_int(slope); // slope
    xdr_int(tmax); // tmax, the maximum time between metrics
    xdr_int(dmax); // dmax, the maximum data value

    xdr_int(1); /*Num of the entries in extra_value field for 
                  Ganglia 3.1.x*/
    xdr_string("GROUP"); /*Group attribute*/
    xdr_string(groupName); /*Group value*/

    for (SocketAddress socketAddress : metricsServers) {
        DatagramPacket packet = new DatagramPacket(buffer, offset, socketAddress);
        datagramSocket.send(packet);
    }

    // Now we send out a message with the actual value.
    // Technically, we only need to send out the metadata message once for
    // each metric, but I don't want to have to record which metrics we did and
    // did not send.
    offset = 0;
    xdr_int(133); // we are sending a string value
    xdr_string(hostName); // hostName
    xdr_string(name); // metric name
    xdr_int(0); // spoof = False
    xdr_string("%s"); // format field
    xdr_string(value); // metric value

    for (SocketAddress socketAddress : metricsServers) {
        DatagramPacket packet = new DatagramPacket(buffer, offset, socketAddress);
        datagramSocket.send(packet);
    }
}

From source file:net.fenyo.gnetwatch.actions.ActionFlood.java

/**
 * Floods the target.//  ww w.j a v a2s  . c om
 * @param none.
 * @return void.
 * @throws IOException IO exception.
 * @throws InterruptedException exception.
 */
public void invoke() throws IOException, InterruptedException {
    if (isDisposed() == true)
        return;

    try {
        super.invoke();

        // il faudrait copier les queriers  la cration de l'action
        final IPQuerier querier;

        DatagramSocket socket;
        final byte[] buf;
        final DatagramPacket packet;
        // on invoque un champ persistent depuis potentiellement un thread autre que celui qu gre une session qui rend cet objet persistent, on doit viter cet accs concurrent (les sessions ne sont pas thread safe)
        synchronized (getGUI().getSynchro()) {
            if (TargetIPv4.class.isInstance(getTarget())) {
                querier = ((TargetIPv4) getTarget()).getIPQuerier();
            } else if (TargetIPv6.class.isInstance(getTarget())) {
                querier = ((TargetIPv6) getTarget()).getIPQuerier();
            } else
                return;

            socket = new DatagramSocket(querier.getPortSrc());
            socket.setTrafficClass(querier.getTos() << 2);
            socket.setBroadcast(true);

            buf = new byte[querier.getPDUMaxSize()];
            Arrays.fill(buf, (byte) 0);
            packet = new DatagramPacket(buf, buf.length,
                    new InetSocketAddress(querier.getAddress(), querier.getPortDst()));
        }

        long last_time = System.currentTimeMillis();
        int bytes_sent = 0;
        while (true) {
            socket.send(packet);
            bytes_sent += buf.length;

            if (System.currentTimeMillis() - last_time > 1000) {

                synchronized (getGUI().getSynchro()) {
                    synchronized (getGUI().sync_tree) {
                        final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            session.update(this);

                            getTarget().addEvent(new EventFlood(new Double(
                                    ((double) 8 * 1000 * bytes_sent) / (System.currentTimeMillis() - last_time))
                                            .intValue()));

                            setDescription(
                                    GenericTools.formatNumericString(getGUI().getConfig(),
                                            "" + new Double(((double) 8 * 1000 * bytes_sent)
                                                    / (System.currentTimeMillis() - last_time)).intValue())
                                            + " bit/s");

                            session.getTransaction().commit();
                        } catch (final Exception ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        }
                    }
                }

                synchronized (getGUI().getSynchro()) {
                    getGUI().setStatus(getGUI().getConfig().getPattern("bytes_flooded", bytes_sent,
                            querier.getAddress().toString().substring(1)));
                }

                last_time = System.currentTimeMillis();
                bytes_sent = 0;
            }

            if (interrupted == true) {
                socket.close();
                return;
            }
        }
    } catch (final InterruptedException ex) {
    }
}

From source file:com.navercorp.pinpoint.profiler.sender.NioUdpDataSenderTest.java

private void waitMessageReceived(int expectReceiveMessageCount) throws IOException {
    byte[] receiveData = new byte[65535];
    DatagramPacket datagramPacket = new DatagramPacket(receiveData, 0, receiveData.length);

    int remainCount = expectReceiveMessageCount;

    while (remainCount > 0) {
        remainCount--;//w  w  w  . j  av  a  2 s .  c  o m
        receiver.receive(datagramPacket);
    }
}

From source file:org.nognog.jmatcher.server.JMatcherDaemonTest.java

/**
 * Test method for {@link org.nognog.jmatcher.JMatcherDaemon#run()}.
 * //from   w  w  w  . ja v  a 2 s.  c o  m
 * @param tcpHandler
 * @param udpHandler
 * 
 * @throws Exception
 */
@SuppressWarnings("unused")
@Test
public final void testConnect(@Mocked final TCPClientRequestHandler tcpHandler,
        @Mocked final UDPClientRequestHandler udpHandler) throws Exception {
    new NonStrictExpectations() {
        {
            new TCPClientRequestHandler((JMatcherDaemon) any, (Socket) any, anyInt);
            result = tcpHandler;
            new UDPClientRequestHandler((JMatcherDaemon) any, (DatagramSocket) any, (InetSocketAddress) any,
                    (String) any, anyInt);
            result = udpHandler;
        }
    };

    final JMatcherDaemon daemon = new JMatcherDaemon();
    daemon.init(null);
    daemon.start();
    try (final Socket socket = new Socket("localhost", JMatcher.PORT)) { //$NON-NLS-1$
        Thread.sleep(100);
        new Verifications() {
            {
                tcpHandler.run();
                times = 1;
                udpHandler.run();
                times = 0;
            }
        };
    }
    try (DatagramSocket socket = new DatagramSocket()) {
        final byte[] buf = "test".getBytes(); //$NON-NLS-1$
        final DatagramPacket packet = new DatagramPacket(buf, buf.length,
                new InetSocketAddress("localhost", JMatcher.PORT)); //$NON-NLS-1$
        socket.send(packet);
        Thread.sleep(100);
        new Verifications() {
            {
                tcpHandler.run();
                times = 1;
                udpHandler.run();
                times = 1;
            }
        };
    }

    daemon.stop();
    daemon.destroy();
}

From source file:PeerDiscovery.java

/**
 * Queries the network and finds the addresses of other peers in
 * the same group//from  www  .j a  va  2s .c  o m
 * 
 * @param timeout
 *           How long to wait for responses, in milliseconds. Call
 *           will block for this long, although you can
 *           {@link Thread#interrupt()} to cut the wait short
 * @param peerType
 *           The type flag of the peers to look for
 * @return The addresses of other peers in the group
 * @throws IOException
 *            If something goes wrong when sending the query packet
 */
public Peer[] getPeers(int timeout, byte peerType) throws IOException {
    responseList = new ArrayList<Peer>();

    // send query byte, appended with the group id
    byte[] data = new byte[5];
    data[0] = QUERY_PACKET;
    encode(group, data, 1);

    DatagramPacket tx = new DatagramPacket(data, data.length, broadcastAddress);

    bcastSocket.send(tx);

    // wait for the listen thread to do its thing
    try {
        Thread.sleep(timeout);
    } catch (InterruptedException e) {
    }

    Peer[] peers;
    synchronized (responseList) {
        peers = responseList.toArray(new Peer[responseList.size()]);
    }

    responseList = null;

    return peers;
}