Example usage for java.net DatagramPacket getData

List of usage examples for java.net DatagramPacket getData

Introduction

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

Prototype

public synchronized byte[] getData() 

Source Link

Document

Returns the data buffer.

Usage

From source file:net.jradius.packet.PacketFactory.java

/**
 * Parse a UDP RADIUS message//from ww w .  ja  va  2  s  .c o  m
 * @param dp The Datagram to be parsed
 * @return Returns the RadiusPacket
 * @throws RadiusException
 */
public static RadiusPacket parse(DatagramPacket dp, boolean pool) throws RadiusException {
    ByteBuffer buffer = ByteBuffer.wrap(dp.getData(), dp.getOffset(), dp.getLength());
    RadiusPacket rp = null;

    try {
        rp = parseUDP(buffer, pool);
    } catch (IOException e) {
        RadiusLog.error(e.getMessage(), e);
    }

    return rp;
}

From source file:org.saintandreas.serket.ssdp.Message.java

public static Message parseMessage(DatagramPacket packet) throws IOException, HttpException {
    Type type;/*from  w  w  w. j a  v a 2  s .  c  om*/
    Map<String, Header> headers = new HashMap<String, Header>();
    String usn = null;

    LineParser parser = new BasicLineParser();
    SessionInputBuffer inBuffer = new ByteArrayInputBuffer(packet.getData());
    String command = inBuffer.readLine();
    Header[] hs = AbstractMessageParser.parseHeaders(inBuffer, 64, 1024, parser);
    for (Header h : hs) {
        headers.put(h.getName(), h);
    }

    if (Message.NOTIFY_START.startsWith(command)) {
        Header h = headers.get("NTS");
        usn = headers.get("USN").getValue();
        if ("ssdp:alive".equals(h.getValue())) {
            // LogFactory.getLog(SSDPTests.class).debug("Notify message alive " + usn);
            type = Type.NOTIFY_ALIVE;
        } else if ("ssdp:update".equals(h.getValue())) {
            // LogFactory.getLog(SSDPTests.class).debug("Notify message update " + usn);
            type = Type.NOTIFY_UPDATE;
        } else if ("ssdp:byebye".equals(h.getValue())) {
            // LogFactory.getLog(SSDPTests.class).debug("Notify message byebye " + usn);
            type = Type.NOTIFY_BYEBYE;
        } else
            throw new RuntimeException("unknown type");
    } else if (Message.SEARCH_START.startsWith(command)) {
        usn = headers.get("ST").getValue();
        // LogFactory.getLog(SSDPTests.class).debug("Search message " + usn);
        type = Type.SEARCH;
    } else if (Message.HTTP_OK_START.startsWith(command)) {
        // LogFactory.getLog(SSDPTests.class).debug("Response message");
        type = Type.RESPONSE;
    } else
        throw new RuntimeException("unknown type");
    return new Message(type, headers, usn, packet,
            new String(packet.getData(), 0, packet.getLength(), Charsets.US_ASCII));
}

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

/***
 * When you receive a datagram that you expect to be a TFTP packet, you use
 * this factory method to create the proper TFTPPacket object
 * encapsulating the data contained in that datagram.  This method is the
 * only way you can instantiate a TFTPPacket derived class from a
 * datagram./* w ww. j  a va 2  s  . co m*/
 * <p>
 * @param datagram  The datagram containing a TFTP packet.
 * @return The TFTPPacket object corresponding to the datagram.
 * @exception TFTPPacketException  If the datagram does not contain a valid
 *             TFTP packet.
 ***/
public final static TFTPPacket newTFTPPacket(DatagramPacket datagram) throws TFTPPacketException {
    byte[] data;
    TFTPPacket packet = null;

    if (datagram.getLength() < MIN_PACKET_SIZE)
        throw new TFTPPacketException("Bad packet. Datagram data length is too short.");

    data = datagram.getData();

    switch (data[1]) {
    case READ_REQUEST:
        packet = new TFTPReadRequestPacket(datagram);
        break;
    case WRITE_REQUEST:
        packet = new TFTPWriteRequestPacket(datagram);
        break;
    case DATA:
        packet = new TFTPDataPacket(datagram);
        break;
    case ACKNOWLEDGEMENT:
        packet = new TFTPAckPacket(datagram);
        break;
    case ERROR:
        packet = new TFTPErrorPacket(datagram);
        break;
    default:
        throw new TFTPPacketException("Bad packet.  Invalid TFTP operator code.");
    }

    return packet;
}

From source file:energy.usef.core.util.DateTimeUtil.java

private static synchronized String getUDPInfo(String message) {
    try {/*from  w  ww .ja v a2  s  .  c o  m*/
        LOGGER.debug("SENDING: {}", message);
        byte[] buf = message.getBytes();
        InetAddress address = InetAddress.getByName(serverIp);
        DatagramSocket socket = new DatagramSocket();
        socket.send(new DatagramPacket(buf, buf.length, address, port));
        DatagramPacket result = new DatagramPacket(new byte[PACKAGE_BUFFER], PACKAGE_BUFFER);
        socket.disconnect();
        socket.setSoTimeout(RESPONSE_TIMEOUT);
        socket.receive(result);
        socket.disconnect();
        socket.close();
        String resultStr = new String(result.getData()).trim();
        LOGGER.debug("RECEIVED: {} ", resultStr);
        errorCount = 0;
        return resultStr;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        errorCount++;
        if (errorCount >= MAX_ERROR_COUNT) {
            LOGGER.error("Unable to run simulation correctly.");
            System.exit(1);
        }
    }
    return null;
}

From source file:org.cc86.MMC.client.Main.java

public static String serverDiscovery() {
    String res = "0.0.0.0";
    DatagramSocket c;/*w w  w  .j a va2s  .co  m*/
    // Find the server using UDP broadcast
    try {
        //Open a random port to send the package
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 0xCC86);
            c.send(sendPacket);
            l.info("Request packet sent to: 255.255.255.255 (DEFAULT)");
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }

                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }

                l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: "
                        + networkInterface.getDisplayName());
            }
        }

        l.info("Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_MMC_RESPONSE")) {
            //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            res = (receivePacket.getAddress() + "").substring(1);
        }

        //Close the port!
        c.close();
    } catch (IOException ex) {

    }
    return res;
}

From source file:gravity.android.discovery.DiscoveryClient.java

public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) {
    ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>();

    try {/*from   w  w  w.  j av a 2s .  c  o  m*/
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.setBroadcast(true);
        InetAddress IPAddress = Utils.getBroadcastAddress(mWifi);
        Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress());
        byte[] receiveData = new byte[2048];
        byte[] sendData = new byte[128];

        sendData = token.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        Log.v("DISCOVERY_CLIENT", "sent " + token);
        clientSocket.send(sendPacket);

        long t1 = System.currentTimeMillis();
        while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            try {
                clientSocket.setSoTimeout(500);
                clientSocket.receive(receivePacket);

                if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) {
                    String discovered_name, discovered_ip;
                    int discovered_port;

                    String received = new String(receivePacket.getData());

                    if (received != null) {
                        received = received.trim().substring(0, receivePacket.getLength()).trim();
                        Log.d("Recieved Msg Packet:", received);

                        //StringTokenizer st = new StringTokenizer(received, ",");

                        //Gravity Code
                        JSONObject recievedJson = new JSONObject(received);

                        try {
                            //discovered_name = st.nextToken();   
                            discovered_name = recievedJson.getString("name"); //Gravity code

                            discovered_ip = receivePacket.getAddress().getHostAddress();

                            //discovered_port = Integer.parseInt(st.nextToken());
                            discovered_port = recievedJson.getInt("port_to_share"); //Gravity code

                            Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip
                                    + ":" + discovered_port);

                            boolean add = true;
                            if (ret.size() > 0) {
                                for (DiscoveryServerInfo dsi : ret) {
                                    if (dsi != null && dsi.ip.equals(discovered_ip)) {
                                        add = false;
                                        break;
                                    }
                                }
                            }

                            if (add) {
                                ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip,
                                        discovered_port));
                            }
                        } catch (NoSuchElementException nsee) {
                            Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage());
                        }

                    }
                }

            } catch (SocketTimeoutException tex) {
                /* ignored */ }
        }

        clientSocket.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.e("DISCOVERY_CLIENT", ex.toString());
    }

    return ret;
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Attempts to discover peer clusters using Multicast
 * Discovery. Each discovered Cluster will be notified
 * to the {@code PeerClusterService} of the 
 * ClusterManager./*from  w w  w  . j  a v  a  2  s.c o  m*/
 * 
 * @throws IOException if occurred during process
 */
public static void discoverPeerClusters() throws IOException {

    // Only allowed for ClusterManagers
    if (!Grid.isClusterManager()) {
        throw new UnsupportedOperationException(
                "Multicast Discovery Service can be enabled only for ClusterManagers");
    }

    log.info("[MulticastDiscovery] Discovering Peer Clusters...");

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Response Socket
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Set Socket Timeout
    resSock.setSoTimeout((int) TIMEOUT);

    try {

        // Loop until Socket Timeout Occurs
        while (true) {

            // Receive
            resSock.receive(response);
            processPeerResponse(response.getData());

        }

    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    } finally {
        log.info("[MulticastDiscovery] Peer Cluster Discovery Complete");
    }

}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Starts Multicast Discovery Service. This can only
 * be invoked by a Nebula ClusterManager.
 * //w w  w.  j a v  a 2s.  c o  m
 * @throws IOException if occurred during operation
 * @throws UnsupportedOperationException if invoked by non-ClusterManager nodes.
 */
public static void startService() throws IOException, UnsupportedOperationException {

    // Only allowed for ClusterManagers
    if (!Grid.isClusterManager()) {
        throw new UnsupportedOperationException(
                "Multicast Discovery Service can be enabled only for ClusterManagers");
    }

    // Start Service
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {

                // Start Multicast Socket and listen for Requests
                final MulticastSocket mSock = new MulticastSocket(SERVICE_PORT);
                mSock.joinGroup(SERVICE_REQUEST_IP);

                // Infinite Loop
                while (true) {
                    // Buffer (for Greeting Message)
                    byte[] msg = new byte[GREET_MSG.getBytes("UTF-8").length];

                    // Create Datagram Packet
                    DatagramPacket packet = new DatagramPacket(msg, msg.length);

                    // Wait and Receive Request
                    mSock.receive(packet);
                    log.debug("[MulticastDiscovery] Received Discovery Request");

                    // Check if Greeting Message is valid
                    try {
                        String greet = new String(packet.getData());
                        if (!greet.equals(GREET_MSG)) {
                            throw new IllegalArgumentException("Invalid Greeting");
                        }
                    } catch (Exception e) {
                        log.debug("Malformed Multicast Message Igonored");
                        continue;
                    }

                    // Respond
                    doRespond();
                }

            } catch (IOException e) {
                log.error("[MulticastDiscovery] Service Failed on Receive", e);
            }

        }

    });
    t.setDaemon(true); // Run as Daemon thread
    t.start(); // Start Service
    log.debug("[MulticastDiscovery] Service Started");
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Starts up two threads: one to broadcast UPnP ALIVE messages and another
 * to listen for responses. /*from w w w  .j  a va 2  s  . co  m*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void listen() throws IOException {
    Runnable rAlive = new Runnable() {
        @Override
        public void run() {
            int delay = 10000;

            while (true) {
                sleep(delay);
                sendAlive();

                // The first delay for sending an ALIVE message is 10 seconds,
                // the second delay is for 20 seconds. From then on, all other
                // delays are for 180 seconds.
                switch (delay) {
                case 10000:
                    delay = 20000;
                    break;
                case 20000:
                    delay = 180000;
                    break;
                }
            }
        }
    };

    aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender");
    aliveThread.start();

    Runnable r = new Runnable() {
        @Override
        public void run() {
            boolean bindErrorReported = false;

            while (true) {
                MulticastSocket multicastSocket = null;

                try {
                    // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166
                    multicastSocket = new MulticastSocket(configuration.getUpnpPort());

                    if (bindErrorReported) {
                        logger.warn(
                                "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!");
                    }

                    NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName();

                    try {
                        // Setting the network interface will throw a SocketException on Mac OSX
                        // with Java 1.6.0_45 or higher, but if we don't do it some Windows
                        // configurations will not listen at all.
                        if (ni != null) {
                            multicastSocket.setNetworkInterface(ni);
                        } else if (PMS.get().getServer().getNetworkInterface() != null) {
                            multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface());
                            logger.trace("Setting multicast network interface: "
                                    + PMS.get().getServer().getNetworkInterface());
                        }
                    } catch (SocketException e) {
                        // Not setting the network interface will work just fine on Mac OSX.
                    }

                    multicastSocket.setTimeToLive(4);
                    multicastSocket.setReuseAddress(true);
                    InetAddress upnpAddress = getUPNPAddress();
                    multicastSocket.joinGroup(upnpAddress);

                    while (true) {
                        byte[] buf = new byte[1024];
                        DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
                        multicastSocket.receive(receivePacket);

                        String s = new String(receivePacket.getData());

                        InetAddress address = receivePacket.getAddress();

                        if (s.startsWith("M-SEARCH")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            if (configuration.getIpFiltering().allowed(address)) {
                                logger.trace(
                                        "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]");

                                if (StringUtils.indexOf(s,
                                        "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:service:ContentDirectory:1");
                                }

                                if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) {
                                    sendDiscover(remoteAddr, remotePort, "upnp:rootdevice");
                                }

                                if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, "ssdp:all") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, PMS.get().usn()) > 0) {
                                    sendDiscover(remoteAddr, remotePort, PMS.get().usn());
                                }
                            }
                        } else if (s.startsWith("NOTIFY")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]");
                        }
                    }
                } catch (BindException e) {
                    if (!bindErrorReported) {
                        logger.error("Unable to bind to " + configuration.getUpnpPort()
                                + ", which means that PMS will not automatically appear on your renderer! "
                                + "This usually means that another program occupies the port. Please "
                                + "stop the other program and free up the port. "
                                + "PMS will keep trying to bind to it...[" + e.getMessage() + "]");
                    }

                    bindErrorReported = true;
                    sleep(5000);
                } catch (IOException e) {
                    logger.error("UPNP network exception", e);
                    sleep(1000);
                } finally {
                    if (multicastSocket != null) {
                        // Clean up the multicast socket nicely
                        try {
                            InetAddress upnpAddress = getUPNPAddress();
                            multicastSocket.leaveGroup(upnpAddress);
                        } catch (IOException e) {
                        }

                        multicastSocket.disconnect();
                        multicastSocket.close();
                    }
                }
            }
        }
    };

    listenerThread = new Thread(r, "UPNPHelper");
    listenerThread.start();
}

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

/**
 * Extracts an IPC port from the given datagram packet. The datagram packet must be of the type
 * <code>JM_LOOKUP_REPLY_PACKET_ID</code>.
 * /*from   ww w  .  j  a va  2  s  . com*/
 * @param packet
 *        the packet to extract the IPC port from.
 * @return the extracted IPC port or <code>-1</code> if the port could not be extracted
 */
private static int extractIpcPort(DatagramPacket packet) {

    final byte[] data = packet.getData();

    if (data == null) {
        return -1;
    }

    if (packet.getLength() < (PAYLOAD_OFFSET + 4)) {
        return -1;
    }

    return byteArrayToInteger(data, PAYLOAD_OFFSET);
}