Example usage for java.net DatagramPacket getAddress

List of usage examples for java.net DatagramPacket getAddress

Introduction

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

Prototype

public synchronized InetAddress getAddress() 

Source Link

Document

Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.

Usage

From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {/*from  www  . j a va  2 s.  co  m*/
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}

From source file:com.iiitd.networking.UDPMessenger.java

public void startMessageReceiver() {
    Runnable receiver = new Runnable() {

        @Override/*from w w  w  . ja v a2  s.c  om*/
        public void run() {
            WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (wim != null) {
                MulticastLock mcLock = wim.createMulticastLock(TAG);
                mcLock.acquire();
            }

            byte[] buffer = new byte[BUFFER_SIZE];
            DatagramPacket rPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket rSocket;

            try {
                rSocket = new MulticastSocket(MULTICAST_PORT);
            } catch (IOException e) {
                Log.d(DEBUG_TAG, "Impossible to create a new MulticastSocket on port " + MULTICAST_PORT);
                e.printStackTrace();
                return;
            }

            while (receiveMessages) {
                try {
                    rSocket.receive(rPacket);
                } catch (IOException e1) {
                    Log.d(DEBUG_TAG, "There was a problem receiving the incoming message.");
                    e1.printStackTrace();
                    continue;
                }

                if (!receiveMessages)
                    break;

                byte data[] = rPacket.getData();
                int i;
                for (i = 0; i < data.length; i++) {
                    if (data[i] == '\0')
                        break;
                }

                String messageText;

                try {
                    messageText = new String(data, 0, i, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    Log.d(DEBUG_TAG, "UTF-8 encoding is not supported. Can't receive the incoming message.");
                    e.printStackTrace();
                    continue;
                }

                try {
                    incomingMessage = new Message(messageText, rPacket.getAddress());
                } catch (IllegalArgumentException ex) {
                    Log.d(DEBUG_TAG, "There was a problem processing the message: " + messageText);
                    ex.printStackTrace();
                    continue;
                }

                incomingMessageHandler.post(getIncomingMessageAnalyseRunnable());
            }
        }

    };

    receiveMessages = true;
    if (receiverThread == null)
        receiverThread = new Thread(receiver);

    if (!receiverThread.isAlive())
        receiverThread.start();
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

public void run() {
    InetAddress group = null;// w w w  .  j  a v a 2  s .  c  o m
    try {
        group = InetAddress.getByName("239.255.255.250");
        skt = new java.net.MulticastSocket(1900);
        skt.setInterface(bindAddress.getAddress());
        skt.joinGroup(group);
    } catch (IOException ex) {
        log.error("Error during multicast socket creation, thread cannot start", ex);
        return;
    }
    isRunning = true;
    while (isRunning) {
        try {
            byte[] buffer = new byte[4096];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, bindAddress.getPort());
            skt.receive(packet);
            String received = new String(packet.getData(), 0, packet.getLength());
            if (log.isDebugEnabled())
                log.debug("Received message:\n" + received);
            HttpRequest req = new HttpRequest(received);
            if (req.getHttpCommand().equals("M-SEARCH")) {
                String man = req.getHTTPHeaderField("MAN");
                if (man.equals("\"ssdp:discover\"")) {
                    String searchTarget = req.getHTTPHeaderField("ST");
                    // TODO check ALL devices search target
                    //if ( searchTarget.equals( Discovery.ALL_DEVICES ) ) {
                    if (searchTarget.equals(Discovery.ROOT_DEVICES)) {
                        java.net.MulticastSocket multi = new java.net.MulticastSocket();
                        multi.setInterface(bindAddress.getAddress());
                        for (Iterator i = handledDevices.iterator(); i.hasNext();) {
                            UPNPMBeanDevice dv = (UPNPMBeanDevice) i.next();
                            List packets = getReplyMessages(dv, false, dv.getSSDPAliveDelay());
                            for (int z = 0; z < packets.size(); z++) {
                                String pack = (String) packets.get(z);
                                if (log.isDebugEnabled())
                                    log.debug("Sending http reply message on " + packet.getAddress() + ":"
                                            + packet.getPort() + " multicast address:\n" + pack.toString());
                                byte[] pk = pack.getBytes();
                                multi.setTimeToLive(dv.getSSDPTTL());
                                multi.send(new DatagramPacket(pk, pk.length, packet.getAddress(),
                                        packet.getPort()));
                            }
                        }
                        multi.close();
                    } else {
                        // TODO check a specific search target
                    }
                }
            }
        } catch (IOException ex) {
            if (isRunning) {
                log.error("Error during multicast socket IO operations", ex);
            }
        }
    }
}

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

private void processPacket(DatagramPacket packet) {
    try {//from   w w w.j a  v  a 2  s  .co 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:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Server side implementation of Discovery Service.
 *//*w w w.ja v  a  2  s  .  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();
}

From source file:ru.novoscan.trkpd.snmp.spring.TrackSpringSnmpAgent.java

public void run() {
    try {//w w w  .j a va  2 s. c  o  m
        logger.debug("Binding to UDP port " + listeningPort);
        socket = new DatagramSocket(listeningPort);
    } catch (SocketException e) {
        // Fix: Flag to control lock socket within application
        isSocketException = true;
        throw new SnmpSystemException("Can not create SNMP agent UDP socket. Reason: " + e.getMessage());
    }

    // Fix: Flag to control lock socket within application
    isSocketCreated = true;

    while (!workerThread.isInterrupted()) {
        byte requestPacketBuffer[] = new byte[PACKET_MAX_SIZE];
        final DatagramPacket requestPacket = new DatagramPacket(requestPacketBuffer,
                requestPacketBuffer.length);
        try {
            socket.receive(requestPacket);
        } catch (IOException e) {
            logger.error("Error processing SNMP request. Reason: " + e.getMessage());
            continue;
        }
        final byte data[] = requestPacket.getData();
        Thread procThread = new Thread(new Runnable() {

            public void run() {
                try {
                    Message requestMsg;
                    Message responseMsg;
                    PDU requestPDU;
                    // Fix: Added missed ')' character
                    logger.debug("Received packet (length=" + data.length + " bytes)");
                    BerTlv tlv = new BerTlv();
                    tlv.decode(new ByteArrayInputStream(data));
                    requestMsg = new Message(tlv);
                    responseMsg = null;
                    requestPDU = (PDU) requestMsg.getPDU();
                    String requestedOID = requestPDU.getVarBindList().getVarBind(0).getObjectName()
                            .stringValue();

                    if (!hasHandledPrefix(requestedOID)) {

                        logger.info("No entry found for oid " + requestedOID);
                        GetResponsePDU responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 2, 0L,
                                requestPDU.getVarBindList());
                        responseMsg = new Message(0, requestMsg.getComunity(), responsePDU);

                        return;
                    }

                    if (!validateCommunity(requestMsg)) {
                        logger.warn(
                                "Community [" + requestMsg.getComunity() + "] doesn't match for snmp request");
                        return;
                    }

                    GetResponsePDU responsePDU = null;
                    if (requestPDU instanceof GetRequestPDU)
                        responsePDU = handleGetRequest((GetRequestPDU) requestPDU);
                    else if (requestPDU instanceof GetNextRequestPDU)
                        responsePDU = handleGetNextRequest((GetNextRequestPDU) requestPDU);
                    else if (requestPDU instanceof SetRequestPDU)
                        responsePDU = handleSetRequest((SetRequestPDU) requestPDU);
                    else
                        responsePDU = createErrorResponse(requestPDU.getRequestId(), 5, 0,
                                requestPDU.getVarBindList());
                    responseMsg = new Message(0, requestMsg.getComunity(), responsePDU);

                    logger.info("Sending response to client\n" + responseMsg.toString());
                    byte responsePacketBuffer[] = responseMsg.toBerTlv().getBytes();
                    if (responsePacketBuffer.length > PACKET_MAX_SIZE) {
                        responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 1, 0L,
                                requestPDU.getVarBindList());
                        responseMsg = new Message(SNMP_VERSION, requestMsg.getComunity(), responsePDU);
                        responsePacketBuffer = responseMsg.toBerTlv().getBytes();
                    }
                    DatagramPacket responsePacket = new DatagramPacket(responsePacketBuffer,
                            responsePacketBuffer.length, requestPacket.getAddress(), requestPacket.getPort());
                    socket.send(responsePacket);
                } catch (Exception e) {
                    logger.error("Error processing SNMP request. Reason: " + e.getMessage());
                }
            }
        });
        procThread.start();
    }
}