How to send an M-SEARCH request using Java

I have a Roku device on my network and I want it to be detectable with the program. The official documentation The official Roku documentation reports:

There is a standard SSDP multicast address and port (239.255.255.250:1900), which is used for communication over a local network. Roku responds to M-SEARCH requests for this IP address and port.

To request the roku ip address, your program can send the following request using the http protocol to port 239.255.255.250 1900:

They give an example of using netcat, and they say that wirehark can be used to find the result. They also say:

An external control protocol allows you to control your Roku through a network. The external control service is discovered through SSDP (Simple Service Discovery Protocol). The service is a simple RESTful API that programs can access in almost any programming environment.

I have a java program that manages my Roku with its IP address, and I would like to implement a function that detects it on the network using this SSDP.

How to send an M-SEARCH request using java? I have absolutely no concept how to do this. Is it like a request to receive / send? If anyone could point me in the right direction, I would be very grateful!

+4
source share
1 answer

java-:

/* multicast SSDP M-SEARCH example for 
 * finding the IP Address of a Roku
 * device. For more info go to: 
 * http://sdkdocs.roku.com/display/sdkdoc/External+Control+Guide 
 */

import java.io.*;
import java.net.*;

class msearchSSDPRequest {
    public static void main(String args[]) throws Exception {
        /* create byte arrays to hold our send and response data */
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        /* our M-SEARCH data as a byte array */
        String MSEARCH = "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\nST: roku:ecp\n"; 
        sendData = MSEARCH.getBytes();

        /* create a packet from our data destined for 239.255.255.250:1900 */
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);

        /* send packet to the socket we're creating */
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.send(sendPacket);

        /* recieve response and store in our receivePacket */
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);

        /* get the response as a string */
        String response = new String(receivePacket.getData());

        /* print the response */
        System.out.println(response);

        /* close the socket */
        clientSocket.close();
    }
}
+4

All Articles