Example usage for java.net DatagramPacket getSocketAddress

List of usage examples for java.net DatagramPacket getSocketAddress

Introduction

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

Prototype

public synchronized SocketAddress getSocketAddress() 

Source Link

Document

Gets the SocketAddress (usually IP address + port number) of the remote host that this packet is being sent to or is coming from.

Usage

From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java

@Override
public void run() {
    if (parent.getRemote() == null) {
        throw new IllegalArgumentException("No user data set for remote user");
    }/* w w w .  ja va2s. c  o m*/

    logger.info("Started listening to port: " + port);
    while (running && channel.isBound()) {

        byte[] bt = new byte[bufferSize];

        try {
            if (mode == ConnectionMode.BINDING) {
                logger.info("Listening for binding on: " + channel.getLocalSocketAddress() + " - "
                        + channel.getPort());
                Thread.sleep(5); //No reason to hammer on this

                DatagramPacket packet = new DatagramPacket(bt, 0, bt.length);
                channel.receive(packet);
                SocketAddress currentSender = packet.getSocketAddress();

                sender = currentSender;
                byte[] data = Arrays.copyOf(packet.getData(), packet.getLength());
                logger.info("Received data: " + Hex.encodeHexString(data) + " on "
                        + channel.getLocalSocketAddress() + " - " + channel.getPort());

                byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(),
                        parent.getLocal().getPassword(), (InetSocketAddress) currentSender);

                ByteBuffer outData = ByteBuffer.wrap(out);
                logger.info("Sending: " + Hex.encodeHexString(outData.array()) + " to " + currentSender);

                DatagramPacket pc = new DatagramPacket(out, 0, out.length);
                pc.setSocketAddress(sender);
                channel.send(pc);

                this.mode = ConnectionMode.HANDSHAKE; //Go to handshake mode
                logger.info("-> DTLS handshake");
            } else if (mode == ConnectionMode.HANDSHAKE) {
                Thread.sleep(5);
                logger.info("In handshake mode: ");

                if (transport == null) {
                    channel.connect(sender);

                    /**
                     * {@link NioUdpTransport} might replace the {@link UDPTransport} here.
                     * @see <a href="https://github.com/RestComm/mediaserver/blob/master/io/rtp/src/main/java/org/mobicents/media/server/impl/srtp/NioUdpTransport.java">NioUdpTransport</a>
                     */
                    transport = serverProtocol.accept(dtlsServer,
                            new DtlsMuxStunTransport(parent, channel, MTU));
                }

                sctpService = new SCTPImpl(this);

                mode = ConnectionMode.TRANSFER;
                logger.info("-> SCTP mode");
            } else if (mode == ConnectionMode.TRANSFER) {

                /**
                 * Here we receive message and put them to a worker thread for handling
                 * If the output of handling the message is a message, then we send those
                 * using the same thread.
                 */
                byte[] buf = new byte[transport.getReceiveLimit()];
                int length = transport.receive(buf, 0, buf.length, waitMillis);
                if (length >= 0) {
                    byte[] handled = Arrays.copyOf(buf, length);
                    workPool.submit(() -> {
                        try {
                            List<byte[]> data = sctpService.handleRequest(handled);
                            data.forEach(this::putDataOnWire);
                        } catch (Exception e) {
                            logger.error("Failed handling message: ", e);
                        }
                    });
                    logger.debug("Input: " + Hex.encodeHexString(handled));
                }
            }
        } catch (Exception e) {
            logger.error("Com error:", e);
            logger.info("Shutting down, we cannot continue here");
            running = false; //Need to quit channel now
        }
    }
    workPool.shutdown();
}

From source file:ca.viaware.dlna.ssdp.SSDPService.java

public void handleCommand(String data, DatagramPacket packet) {
    HttpParser parser = new HttpParser();
    parser.parseRequest(data);//  www . j  a  v  a2  s  .co m

    if (parser.getMethod().equals("M-SEARCH")) {
        String st = parser.getHeader("st");

        if (st.equals("ssdp:all")) {
            for (Device d : DeviceManager.getDevices()) {
                reply("upnp:rootdevice", "uuid:" + d.getUid() + "::upnp:rootdevice", d.getUid(),
                        packet.getSocketAddress());
                reply("uuid:" + d.getUid(), "uuid:" + d.getUid(), d.getUid(), packet.getSocketAddress());
                reply("urn:schemas-upnp-org:device:" + d.getType() + ":" + d.getVersion(), "uuid:" + d.getUid()
                        + "::urn:schemas-upnp-org:device:" + d.getType() + ":" + d.getVersion(), d.getUid(),
                        packet.getSocketAddress());
                for (Service s : d.getServices()) {
                    reply("urn:schemas-upnp-org:service:" + s.getType() + ":" + s.getVersion(),
                            "uuid:" + d.getUid() + "::urn:schemas-upnp-org:service:" + s.getType() + ":"
                                    + s.getVersion(),
                            d.getUid(), packet.getSocketAddress());
                }
            }
        } else if (st.equals("upnp:rootdevice")) {

            for (Device d : DeviceManager.getDevices()) {
                reply(st, "uuid:" + d.getUid() + "::upnp:rootdevice", d.getUid(), packet.getSocketAddress());
            }

        } else if (st.startsWith("uuid")) {

            for (Device d : DeviceManager.getDevices()) {
                if (parser.getHeader("st").contains(d.getUid())) {
                    String usn = "uuid:" + d.getUid();
                    reply(st, usn, d.getUid(), packet.getSocketAddress());
                    break;
                }
            }

        } else {
            for (Device d : DeviceManager.getDevices()) {
                if (st.equals("urn:schemas-upnp-org:device:" + d.getUid() + ":" + d.getVersion())) {
                    String usn = "uuid:" + d.getUid() + "::" + st;
                    reply(st, usn, d.getUid(), packet.getSocketAddress());
                    break;
                } else {
                    for (Service s : d.getServices()) {
                        if (st.equals("urn:schemas-upnp-org:service:" + s.getUid() + ":" + s.getVersion())) {
                            String usn = "uuid:" + d.getUid() + "::" + st;
                            reply(st, usn, d.getUid(), packet.getSocketAddress());
                            break;
                        }
                    }
                }
            }
        }
    }

}

From source file:org.zxg.network.dhtcrawler.Crawler.java

@Override
protected UdpMsg recvUdp() throws IOException {
    byte[] buffer = new byte[65536];
    DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
    socket.receive(datagramPacket);/*w  w w .j a v a 2 s. co m*/
    UdpMsg msg = new UdpMsg();
    msg.data = new byte[datagramPacket.getLength()];
    System.arraycopy(datagramPacket.getData(), datagramPacket.getOffset(), msg.data, 0,
            datagramPacket.getLength());
    InetSocketAddress socketAddress = (InetSocketAddress) datagramPacket.getSocketAddress();
    msg.addr = new Addr(socketAddress.getHostString(), socketAddress.getPort());
    return msg;
}

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

private void processPacket(DatagramPacket packet) {
    try {//from  w ww . j  a  v a  2 s. c o m
        PEBinaryReader reader = new PEBinaryReader(new ByteArrayInputStream(packet.getData()));
        int raknetPID = reader.readByte() & 0xFF;
        switch (raknetPID) {
        case RaknetConstants.ID_PING_OPEN_CONNECTIONS:
            ServerInfoPacket pkReply = new ServerInfoPacket();
            pkReply.time = reader.readLong();
            pkReply.serverID = serverID;
            pkReply.serverName = this.getManager().getServer().getServer().getName();
            pkReply.encode();
            this.udp.send(pkReply.getData(), packet.getSocketAddress());
            break;
        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.readByte();
            reader.readInt();
            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.writeAddress(packet.getAddress(), (short) packet.getPort());
            writer8.writeShort(clientMTU);
            writer8.writeByte((byte) 0x00);
            this.send(bos8.toByteArray(), packet.getSocketAddress());
            PENetworkClient session = new PENetworkClient(this, packet.getSocketAddress(), clientID, clientMTU);
            clients.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.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) {
                RaknetDataPacket dataPacket = new RaknetDataPacket(
                        ArrayUtils.subarray(packet.getData(), 1, packet.getLength()));
                dataPacket.decode();
                clients.get(getClientKey(packet.getSocketAddress())).processDataPacket(dataPacket);
            }
            break;
        case 0xC0:
            if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) {
                clients.get(getClientKey(packet.getSocketAddress()))
                        .processACKPacket(ArrayUtils.subarray(packet.getData(), 1, packet.getData().length));
            }
            break;
        case 0xA0:
            if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) {
                clients.get(getClientKey(packet.getSocketAddress()))
                        .processNACKPacket(ArrayUtils.subarray(packet.getData(), 1, packet.getData().length));
            }
            break;
        }
    } catch (IOException e) {
    }
}

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

private void processPacket(DatagramPacket packet) {
    try {//  www  .  j av a  2 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) {
    }
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Server side implementation of Discovery Service.
 *//* w  w  w . j a  va  2s  .c  o m*/
@Override
public void run() {

    final DatagramPacket requestPacket = new DatagramPacket(new byte[64], 64);

    final Map<Integer, Long> packetIDMap = new HashMap<Integer, Long>();

    while (this.isRunning) {

        try {
            this.serverSocket.receive(requestPacket);

            if (!isPacketForUs(requestPacket, this.magicNumber)) {
                LOG.debug("Received request packet which is not destined to this Nephele setup");
                continue;
            }

            final Integer packetID = Integer.valueOf(extractPacketID(requestPacket));
            if (packetIDMap.containsKey(packetID)) {
                LOG.debug("Request with ID " + packetID.intValue() + " already answered, discarding...");
                continue;
            } else {

                final long currentTime = System.currentTimeMillis();

                // Remove old entries
                final Iterator<Map.Entry<Integer, Long>> it = packetIDMap.entrySet().iterator();
                while (it.hasNext()) {

                    final Map.Entry<Integer, Long> entry = it.next();
                    if ((entry.getValue().longValue() + 5000L) < currentTime) {
                        it.remove();
                    }
                }

                packetIDMap.put(packetID, Long.valueOf(currentTime));
            }

            final int packetTypeID = getPacketTypeID(requestPacket);
            if (packetTypeID == JM_LOOKUP_REQUEST_ID) {

                LOG.debug("Received job manager lookup request from " + requestPacket.getSocketAddress());
                final DatagramPacket responsePacket = createJobManagerLookupReplyPacket(this.ipcPort,
                        this.magicNumber);
                responsePacket.setAddress(requestPacket.getAddress());
                responsePacket.setPort(requestPacket.getPort());

                this.serverSocket.send(responsePacket);

            } else if (packetTypeID == TM_ADDRESS_REQUEST_ID) {
                LOG.debug("Received task manager address request from " + requestPacket.getSocketAddress());
                final DatagramPacket responsePacket = createTaskManagerAddressReplyPacket(
                        requestPacket.getAddress(), this.magicNumber);
                responsePacket.setAddress(requestPacket.getAddress());
                responsePacket.setPort(requestPacket.getPort());

                this.serverSocket.send(responsePacket);

            } else {
                LOG.debug("Received packet of unknown type " + packetTypeID + ", discarding...");
            }

        } catch (SocketTimeoutException ste) {
            LOG.debug("Discovery service: socket timeout");
        } catch (IOException ioe) {
            if (this.isRunning) { // Ignore exception when service has been stopped
                LOG.error("Discovery service stopped working with IOException:\n" + ioe.toString());
            }
            break;
        }
    }

    // Close the socket finally
    this.serverSocket.close();
}