Example usage for java.net DatagramPacket setPort

List of usage examples for java.net DatagramPacket setPort

Introduction

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

Prototype

public synchronized void setPort(int iport) 

Source Link

Document

Sets the port number on the remote host to which this datagram is being sent.

Usage

From source file:examples.ntp.SimpleNTPServer.java

/**
 * Handle incoming packet. If NTP packet is client-mode then respond
 * to that host with a NTP response packet otherwise ignore.
 *
 * @param request incoming DatagramPacket
 * @param rcvTime time packet received//w  w  w.  j  a v  a  2  s.  c  o  m
 *
 * @throws IOException  if an I/O error occurs.
 */
protected void handlePacket(DatagramPacket request, long rcvTime) throws IOException {
    NtpV3Packet message = new NtpV3Impl();
    message.setDatagramPacket(request);
    System.out.printf("NTP packet from %s mode=%s%n", request.getAddress().getHostAddress(),
            NtpUtils.getModeName(message.getMode()));
    if (message.getMode() == NtpV3Packet.MODE_CLIENT) {
        NtpV3Packet response = new NtpV3Impl();

        response.setStratum(1);
        response.setMode(NtpV3Packet.MODE_SERVER);
        response.setVersion(NtpV3Packet.VERSION_3);
        response.setPrecision(-20);
        response.setPoll(0);
        response.setRootDelay(62);
        response.setRootDispersion((int) (16.51 * 65.536));

        // originate time as defined in RFC-1305 (t1)
        response.setOriginateTimeStamp(message.getTransmitTimeStamp());
        // Receive Time is time request received by server (t2)
        response.setReceiveTimeStamp(TimeStamp.getNtpTime(rcvTime));
        response.setReferenceTime(response.getReceiveTimeStamp());
        response.setReferenceId(0x4C434C00); // LCL (Undisciplined Local Clock)

        // Transmit time is time reply sent by server (t3)
        response.setTransmitTime(TimeStamp.getNtpTime(System.currentTimeMillis()));

        DatagramPacket dp = response.getDatagramPacket();
        dp.setPort(request.getPort());
        dp.setAddress(request.getAddress());
        socket.send(dp);
    }
    // otherwise if received packet is other than CLIENT mode then ignore it
}

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

public Void execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket();

    socket.setReuseAddress(true);/*from   ww w. j a  v a 2  s  . c o m*/
    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()));
    if (parameter.getPort() > 0)
        packet.setPort(parameter.getPort());
    socket.send(packet);
    socket.close();
    return null;
}

From source file:org.eredlab.g4.ccl.net.ntp.NTPUDPClient.java

/***
 * Retrieves the time information from the specified server and port and
 * returns it. The time is the number of miliiseconds since
 * 00:00 (midnight) 1 January 1900 UTC, as specified by RFC 1305.
 * This method reads the raw NTP packet and constructs a <i>TimeInfo</i>
 * object that allows access to all the fields of the NTP message header.
 * <p>/*w  w  w.j a  v a 2  s. co m*/
 * @param host The address of the server.
 * @param port The port of the service.
 * @return The time value retrieved from the server.
 * @exception IOException If an error occurs while retrieving the time.
 ***/
public TimeInfo getTime(InetAddress host, int port) throws IOException {
    // if not connected then open to next available UDP port
    if (!isOpen()) {
        open();
    }

    NtpV3Packet message = new NtpV3Impl();
    message.setMode(NtpV3Packet.MODE_CLIENT);
    message.setVersion(_version);
    DatagramPacket sendPacket = message.getDatagramPacket();
    sendPacket.setAddress(host);
    sendPacket.setPort(port);

    NtpV3Packet recMessage = new NtpV3Impl();
    DatagramPacket receivePacket = recMessage.getDatagramPacket();

    /*
     * Must minimize the time between getting the current time,
     * timestamping the packet, and sending it out which
     * introduces an error in the delay time.
     * No extraneous logging and initializations here !!!
     */
    TimeStamp now = TimeStamp.getCurrentTime();

    // Note that if you do not set the transmit time field then originating time
    // in server response is all 0's which is "Thu Feb 07 01:28:16 EST 2036".
    message.setTransmitTime(now);

    _socket_.send(sendPacket);
    _socket_.receive(receivePacket);

    long returnTime = System.currentTimeMillis();
    // create TimeInfo message container but don't pre-compute the details yet
    TimeInfo info = new TimeInfo(recMessage, returnTime, false);

    return info;
}

From source file:org.apache.catalina.cluster.mcast.McastServiceImpl.java

/**
 * Send a ping// w  w w .j a  v a2  s  .c o m
 * @throws Exception
 */
public void send() throws Exception {
    member.inc();
    byte[] data = member.getData(this.serviceStartTime);
    DatagramPacket p = new DatagramPacket(data, data.length);
    p.setAddress(address);
    p.setPort(port);
    socket.send(p);
}

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

/***
 * This is a method only available within the package for
 * implementing efficient datagram transport by elminating buffering.
 * It takes a datagram as an argument, and a byte buffer in which
 * to store the raw datagram data.  Inside the method, the data
 * is set as the datagram's data and the datagram returned.
 * <p>/*from   w w w .  ja  va  2  s . c om*/
 * @param datagram  The datagram to create.
 * @param data The buffer to store the packet and to use in the datagram.
 * @return The datagram argument.
 ***/
DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) {
    data[0] = 0;
    data[1] = (byte) _type;
    data[2] = (byte) ((_blockNumber & 0xffff) >> 8);
    data[3] = (byte) (_blockNumber & 0xff);

    datagram.setAddress(_address);
    datagram.setPort(_port);
    datagram.setData(data);
    datagram.setLength(4);

    return datagram;
}

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

private DatagramPacket buildSearchPacket() {
    try {//from   ww w.  j av  a2 s. c  o  m
        String aSearchCommand = Protocol.Commands.prepareCommand(Protocol.Commands.SEARCH_SERVERS);

        DatagramPacket aSearchPacket = new DatagramPacket(aSearchCommand.getBytes(), aSearchCommand.length());

        aSearchPacket.setAddress(InetAddress.getByName(Protocol.Addresses.SERVER_SEARCH));
        aSearchPacket.setPort(Protocol.Ports.SERVER_SEARCH);

        return aSearchPacket;
    } catch (UnknownHostException e) {
        throw new RuntimeException("Unable to find address to search.");
    }
}

From source file:org.openacs.HostsBean.java

public void RequestConnectionUDP(String url, String user, String pass) throws Exception {
    DatagramSocket s = new DatagramSocket(null);
    s.setReuseAddress(true);/* w w w  . ja va2 s  . c om*/
    s.bind(new InetSocketAddress(Application.getSTUNport()));
    String ts = Long.toString(Calendar.getInstance().getTimeInMillis());
    String id = ts;
    Random rnd = new Random();
    byte[] nonceArray = new byte[16];
    rnd.nextBytes(nonceArray);

    String cn = cvtHex.cvtHex(nonceArray);
    url = url.substring(6);
    String[] u = url.split(":");

    SecretKeySpec signingKey = new SecretKeySpec(pass.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    String data = ts + id + user + cn;
    byte[] rawHmac = mac.doFinal(data.getBytes());
    String signature = cvtHex.cvtHex(rawHmac);
    String req = "GET http://" + url + "?ts=" + ts + "&id=" + id + "&un=" + user + "&cn=" + cn + "&sig="
            + signature + " HTTP/1.1\r\n\r\n";

    byte[] breq = req.getBytes();
    DatagramPacket packet = new DatagramPacket(breq, breq.length);
    packet.setAddress(InetAddress.getByName(u[0]));
    packet.setPort(Integer.parseInt(u[1]));
    s.send(packet);
}

From source file:com.esri.geoevent.test.performance.ClockSync.java

@Override
public void run() {
    DatagramSocket socket = null;
    try {//  w w w . ja  v a 2  s.  c o  m
        byte[] incomingBuffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(incomingBuffer, incomingBuffer.length);

        ByteBuffer bb = ByteBuffer.allocate(8);
        DatagramPacket outgoingPacket = new DatagramPacket(bb.array(), 0, 8, null, port);
        socket = new DatagramSocket(port);
        socket.setSoTimeout(100);
        while (isRunning.get()) {
            try {
                socket.receive(packet);
                long now = System.currentTimeMillis();
                bb.putLong(now);
                outgoingPacket.setAddress(packet.getAddress());
                outgoingPacket.setPort(packet.getPort());
                socket.send(outgoingPacket);
                bb.clear();
                //System.out.println("Sent the time " + now);
            } catch (SocketTimeoutException ex) {
                // Do nothing if nothing was sent.
            }
        }
    } catch (BindException e) {
        // port is in use - increment and try again
        port++;
        this.run();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(socket);
    }
}

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

/***
 * This is a method only available within the package for
 * implementing efficient datagram transport by elminating buffering.
 * It takes a datagram as an argument, and a byte buffer in which
 * to store the raw datagram data.  Inside the method, the data
 * is set as the datagram's data and the datagram returned.
 * <p>/* w w w  .  j  av  a  2  s.  c o m*/
 * @param datagram  The datagram to create.
 * @param data The buffer to store the packet and to use in the datagram.
 * @return The datagram argument.
 ***/
DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) {
    int length;

    length = _message.length();

    data[0] = 0;
    data[1] = (byte) _type;
    data[2] = (byte) ((_error & 0xffff) >> 8);
    data[3] = (byte) (_error & 0xff);

    System.arraycopy(_message.getBytes(), 0, data, 4, length);

    data[length + 4] = 0;

    datagram.setAddress(_address);
    datagram.setPort(_port);
    datagram.setData(data);
    datagram.setLength(length + 4);

    return datagram;
}

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

/***
 * This is a method only available within the package for
 * implementing efficient datagram transport by elminating buffering.
 * It takes a datagram as an argument, and a byte buffer in which
 * to store the raw datagram data.  Inside the method, the data
 * is set as the datagram's data and the datagram returned.
 * <p>/*from www  . jav  a 2 s.  com*/
 * @param datagram  The datagram to create.
 * @param data The buffer to store the packet and to use in the datagram.
 * @return The datagram argument.
 ***/
DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) {
    data[0] = 0;
    data[1] = (byte) _type;
    data[2] = (byte) ((_blockNumber & 0xffff) >> 8);
    data[3] = (byte) (_blockNumber & 0xff);

    // Doublecheck we're not the same
    if (data != _data)
        System.arraycopy(_data, _offset, data, 4, _length);

    datagram.setAddress(_address);
    datagram.setPort(_port);
    datagram.setData(data);
    datagram.setLength(_length + 4);

    return datagram;
}