UPnP device discovery in C# using SSDP

UPnP device discovery in C# using SSDP

UPnP (Universal Plug and Play) is a set of networking protocols that allows devices to discover and communicate with each other on a network. It is used by many consumer devices such as routers, printers, and media players. In this blog post, we will explore how to use C# to discover UPnP devices on a network using the Simple Service Discovery Protocol (SSDP).

The SSDP protocol is a lightweight protocol used to discover UPnP devices on a network. It works by sending a multicast message to all devices on the network, asking for responses from devices that support the protocol. The responses contain information about the device, including its IP address, port number, and services it supports.

To use SSDP in C#, we can use the System.Net.Sockets namespace to send a multicast message and receive responses from devices. Here is a sample that demonstrates how to discover UPnP devices using SSDP:

using System.Net.Sockets;
using System.Net;
using System.Text;

IPEndPoint LocalEndPoint = new IPEndPoint(IPAddress.Parse("10.0.0.52"), 1901);      // modify with your local ip address
IPEndPoint MulticastEndPoint = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);

Socket UdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

UdpSocket.Bind(LocalEndPoint);

string SearchString = "M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nMAN:\"ssdp:discover\"\r\nST:ssdp:all\r\nMX:3\r\n\r\n";
UdpSocket.SendTo(Encoding.UTF8.GetBytes(SearchString), SocketFlags.None, MulticastEndPoint);

byte[] ReceiveBuffer = new byte[64000];
int ReceivedBytes = 0;

while (true)
{
    if (UdpSocket.Available > 0)
    {
        ReceivedBytes = UdpSocket.Receive(ReceiveBuffer, SocketFlags.None);

        if (ReceivedBytes > 0)
        {
            Console.WriteLine(Encoding.UTF8.GetString(ReceiveBuffer, 0, ReceivedBytes));
        }
    }
}

This function sends an SSDP search message to all devices on the network and listens for responses. When a response is received, it is printed to the console. You might receive the same answer from the same devices multiple times, so some filtering might be necessary.

Here’s an example of an answer:

HTTP/1.1 200 OK
Cache-Control: max-age=3600
ST: upnp:rootdevice
USN: uuid:29884002-0207-10c5-8019-88dea1106581::upnp:rootdevice
Ext:
Server: Roku/12.0.0 UPnP/1.0 Roku/12.0.0
LOCATION: http://10.0.0.171:8060/

That’s it! With just a few lines of code, you can discover UPnP devices on your network using C# and SSDP.