Example usage for java.net DatagramPacket getPort

List of usage examples for java.net DatagramPacket getPort

Introduction

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

Prototype

public synchronized int getPort() 

Source Link

Document

Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.

Usage

From source file:com.kecso.socket.ServerSocketControl.java

@Override
public void run() {
    DatagramSocket sock = null;//from  w  w  w.jav a2  s . c o  m

    try {
        sock = new DatagramSocket(8888);
        sock.setSoTimeout(1000);

        byte[] buffer = new byte[65536];
        DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

        while (!Thread.currentThread().isInterrupted()) {
            try {
                sock.receive(incoming);
                byte[] data = incoming.getData();
                this.udpMessage = SerializationUtils.deserialize(data);

                byte[] response = SerializationUtils.serialize(
                        this.output != null
                                ? new UdpResponse((float) output.getSpeed(), (float) output.getVerticalSpeed(),
                                        (float) output.getAltitude(), (float) output.getRpm())
                                : null);
                DatagramPacket dp = new DatagramPacket(response, response.length, incoming.getAddress(),
                        incoming.getPort());
                sock.send(dp);
            } catch (SocketTimeoutException e) {
            }
        }
    } catch (Exception e) {
        System.err.println("IOException " + e);
    } finally {
        if (sock != null) {
            sock.close();
        }

    }
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ??awakeAgent?/*w  w w .  j  av a 2s.c o m*/
 * Agent.properties???UDP?24005??????????(releaseLatch)
 * ????ReceiveTopic????Topic????
 */
public void waitAwakeAgent() {
    final int BUFSIZE = 1;

    byte[] buf = new byte[BUFSIZE];
    InetAddress cAddr; // ??IP
    int cPort; // ???
    DatagramSocket sock = null;
    boolean flag = true;
    int port = 24005;

    int awakeDelay = 1000;

    try {
        String awakeDelayStr = AgentProperties.getProperty("awake.delay", Integer.toString(1000));
        awakeDelay = Integer.parseInt(awakeDelayStr);
        m_log.info("awake.delay = " + awakeDelay + " msec");
    } catch (NumberFormatException e) {
        m_log.error("awake.delay", e);
    }

    while (true) {
        /*
         * UDP???flag?true??
         * ?????flag?false?????getTopic(releaseLatch)?
         * 
         * UDP???????getTopic????????
         * ??????
         */
        try {
            if (sock != null && port != awakePort) {
                sock.close();
                sock = null;
            }
            if (sock == null || !sock.isBound()) {
                port = awakePort;
                sock = new DatagramSocket(port);
                sock.setSoTimeout(awakeDelay);
            }
            DatagramPacket recvPacket = new DatagramPacket(buf, BUFSIZE);
            sock.receive(recvPacket);
            cAddr = recvPacket.getAddress();
            cPort = recvPacket.getPort();
            flag = true;
            m_log.info("waitAwakeAgent (" + cAddr.getHostAddress() + " onPort=" + cPort + ") buf.length="
                    + buf.length);
        } catch (SocketTimeoutException e) {
            if (flag) {
                m_log.info("waitAwakeAgent packet end");
                m_receiveTopic.releaseLatch();
                flag = false;
            }
        } catch (Exception e) {
            String msg = "waitAwakeAgent port=" + awakePort + ", " + e.getClass().getSimpleName() + ", "
                    + e.getMessage();
            if (e instanceof BindException) {
                m_log.warn(msg);
            } else {
                m_log.warn(msg, e);
            }
            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e1) {
                m_log.warn(e1, e1);
            }
        }
    }
}

From source file:org.starnub.starnubserver.servers.starbound.UDPProxyServer.java

public void run() {
    InetAddress IPAddress;// ww  w.  ja  va2  s . c  om
    DatagramSocket ds;
    try {
        ds = new DatagramSocket(starnubPort);
        IPAddress = InetAddress.getByName(starboundAddress);
    } catch (SocketException | UnknownHostException e1) {
        StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e1));
        e1.printStackTrace();
        return;
    }

    byte[] request = new byte[1024];
    byte[] reply = new byte[4096];

    while (!stopping) {
        try {
            DatagramPacket from_client = new DatagramPacket(request, request.length);
            ds.receive(from_client);

            byte[] real_request = new byte[from_client.getLength()];
            System.arraycopy(request, 0, real_request, 0, from_client.getLength());

            DatagramPacket sendPacket = new DatagramPacket(real_request, real_request.length, IPAddress,
                    starboundPort);
            ds.send(sendPacket);

            DatagramPacket from_server = new DatagramPacket(reply, reply.length);
            ds.receive(from_server);
            byte[] real_reply = new byte[from_server.getLength()];
            System.arraycopy(reply, 0, real_reply, 0, from_server.getLength());

            InetAddress address = from_client.getAddress();
            int port = from_client.getPort();
            DatagramPacket to_client = new DatagramPacket(real_reply, real_reply.length, address, port);
            ds.send(to_client);
        } catch (Exception e) {
            StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e));
            return;
        }
    }
}

From source file:Reflector.java

public void packetReceived(DatagramPacket packet) {
    // An incoming packet has been received. Override
    // the old packet addressing to the new outgoing
    // addressing, send it and log it.

    try {//from ww  w . jav a 2  s.  c o m
        packet.setAddress(sendAddr);
        packet.setPort(sendPort);
        ds.send(packet);
        logger.log("Packet forwarded to " + packet.getAddress().getHostAddress() + "/" + packet.getPort() + ", "
                + packet.getLength() + " bytes");
    } catch (IOException e) {
        System.err.println("Error sending packet");
        e.printStackTrace();
    }
}

From source file:org.lockss.test.LockssTestCase.java

/**
 * Asserts that the two DatagramPackets have equal contents
 * @param expected the expected value//from w ww.  j  av  a  2s .co m
 * @param actual the actual value
 */
public static void assertEquals(DatagramPacket expected, DatagramPacket actual) {
    assertEquals(expected.getAddress(), actual.getAddress());
    assertEquals(expected.getPort(), actual.getPort());
    assertEquals(expected.getLength(), actual.getLength());
    assertEquals(expected.getOffset(), actual.getOffset());
    assertTrue(Arrays.equals(expected.getData(), actual.getData()));
}

From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationIncomingMessageHandler.java

/**
 * The main logic of the monitor. Reads in data from the client socket until
 * the client socket is closed/disconnected.
 * /*ww  w  .  j  a v a 2s.  c o m*/
 * @see java.lang.Runnable#run()
 */
public void run() {

    /* Create a Datagram packet to hold the recieved message */
    DatagramPacket pack = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE);

    /* Should the loop keep running? */
    boolean keepRunning = true;

    /* This part loops until we catch an exception */
    while (keepRunning) {

        /* receive messages on the socket */
        try {
            System.out.println("Attempting to recieve a packet");
            newSock.receive(pack);
            System.out.println("RECIEVED A PACKET OMG");
        } catch (IOException e) {
            e.printStackTrace();
            logger.warn(e.getMessage());
        }

        /* put messages into the buffer */
        if (pack.getData() != null) {
            try {
                // List<byte[]> listOfBytes = this.host.getProtocol()
                // .removeProtocol(pack.getData());
                // for (byte[] b : listOfBytes) {
                this.host.getReceiveBuffer().addToBuffer(pack.getData());
                this.host.setRemoteIPAddress(pack.getAddress().getHostAddress());
                this.host.setRemotePort(pack.getPort());

                // }
            } catch (DataBufferInterruptedException e) {
                /* Thrown because socket was interrupted */
                logger.warn(e.getMessage());
                keepRunning = false;
            }

            // catch (ProtocolValidationException e) {
            // /* Thrown because of a problem with the protocol */
            // logger.warn(e.getMessage());
            // }
        }
    }
}

From source file:org.echocat.jomon.net.dns.DnsServer.java

public void serveUDP(InetSocketAddress address) {
    try {//from  www . j  a va  2s.com
        final DatagramSocket sock = new DatagramSocket(address.getPort(), address.getAddress());
        synchronized (_closeables) {
            _closeables.add(sock);
        }
        final short udpLength = 512;
        final byte[] in = new byte[udpLength];
        final DatagramPacket indp = new DatagramPacket(in, in.length);
        DatagramPacket outdp = null;
        while (!currentThread().isInterrupted()) {
            indp.setLength(in.length);
            receive(sock, indp);
            final Message query;
            byte[] response;
            try {
                query = new Message(in);
                response = generateReply(query, in, indp.getLength(), null);
                if (response == null) {
                    continue;
                }
            } catch (final IOException ignored) {
                response = formerrMessage(in);
            }
            if (outdp == null) {
                outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort());
            } else {
                outdp.setData(response);
                outdp.setLength(response.length);
                outdp.setAddress(indp.getAddress());
                outdp.setPort(indp.getPort());
            }
            sock.send(outdp);
        }
    } catch (final InterruptedIOException ignored) {
        currentThread().interrupt();
    } catch (final IOException e) {
        LOG.warn("serveUDP(" + addrport(address.getAddress(), address.getPort()) + ")", e);
    }
}

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//from   w  w w  .j a v  a  2s . 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:org.restcomm.sbc.media.MediaZone.java

public void send(DatagramPacket dgram) throws IOException {

    if (dgram == null)
        return;/*ww w.j ava 2  s.co  m*/

    dgram.setAddress(mediaZonePeer.getOriginalAddress());
    dgram.setPort(mediaZonePeer.getOriginalRtpPort());
    //dgram.setData(mediaZonePeer.encodeRTP(dgram.getData(), 0, dgram.getLength()), 0, dgram.getLength() );   
    //LOG.trace("--->("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+proxyPort+"/"+dgram.getAddress()+":"+dgram.getPort()+"["+dgram.getLength()+"]");   
    //LOG.trace("---> via socket "+toPrint(socket));   
    if (dgram.getData().length > 8) {
        if (logCounter == rtpCountLog) {
            RawPacket rtp = new RawPacket(dgram.getData(), 0, dgram.getLength());
            LOG.trace("--->[PayloadType " + rtp.getPayloadType() + "](" + this.mediaType + ", " + this.direction
                    + ") LocalProxy " + proxyHost + ":" + proxyPort + "/" + dgram.getAddress() + ":"
                    + dgram.getPort() + "[" + dgram.getLength() + "]");
            logCounter = 0;
        }
    } else {
        LOG.warn("--->[PayloadType ?](" + this.mediaType + ", " + this.direction + ") LocalProxy " + proxyHost
                + ":" + proxyPort + "/" + dgram.getAddress() + ":" + dgram.getPort() + "[" + dgram.getLength()
                + "]");
    }

    packetsSentCounter++;

    socket.send(dgram);

}

From source file:org.dragonet.net.NetworkHandler.java

private void processPacket(DatagramPacket packet) {
    try {/*from  w  ww .j  av a2 s.  c  o m*/
        PEBinaryReader reader = new PEBinaryReader(new ByteArrayInputStream(packet.getData()));
        int raknetPID = reader.readByte() & 0xFF;
        switch (raknetPID) {
        case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_1:
            reader.read(16); //MAGIC
            reader.readByte(); //RakNet Protocol
            short mtu = (short) ((packet.getLength() - 18) & 0xFFFF);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PEBinaryWriter writer = new PEBinaryWriter(bos);
            writer.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_1);
            writer.write(RaknetConstants.magic);
            writer.writeLong(NetworkHandler.serverID);
            writer.writeByte((byte) 0x00);
            writer.writeShort(mtu);
            this.udp.send(bos.toByteArray(), packet.getSocketAddress());
            break;
        case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_2:
            reader.read(16);
            reader.read(5);
            reader.readShort();
            short clientMTU = reader.readShort();
            long clientID = reader.readLong();
            ByteArrayOutputStream bos8 = new ByteArrayOutputStream();
            PEBinaryWriter writer8 = new PEBinaryWriter(bos8);
            writer8.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_2);
            writer8.write(RaknetConstants.magic);
            writer8.writeLong(NetworkHandler.serverID);
            writer8.writeShort((short) (packet.getPort() & 0xFFFF));
            writer8.writeShort(clientMTU);
            writer8.writeByte((byte) 0x00);
            this.send(bos8.toByteArray(), packet.getSocketAddress());
            DragonetSession session = new DragonetSession(this.server, packet.getSocketAddress(), clientID,
                    clientMTU);
            this.sessions.put(packet.getSocketAddress().toString(), session);
            //this.server.getServer().getSessionRegistry().add(session);
            break;
        case 0x80:
        case 0x81:
        case 0x82:
        case 0x83:
        case 0x84:
        case 0x85:
        case 0x86:
        case 0x87:
        case 0x88:
        case 0x89:
        case 0x8A:
        case 0x8B:
        case 0x8C:
        case 0x8D:
        case 0x8E:
        case 0x8F:
            if (this.sessions.containsKey(packet.getSocketAddress().toString())) {
                RaknetDataPacket dataPacket = new RaknetDataPacket(
                        ArrayUtils.subarray(packet.getData(), 1, packet.getLength()));
                dataPacket.decode();
                this.sessions.get(packet.getSocketAddress().toString()).processDataPacket(dataPacket);
            }
            break;
        }
    } catch (IOException e) {
    }
}