0

I am trying to access an WeMo light switch using UPnP. After googling many open source c++ libraries I finally figured out a sample code for basic discovery of UPnP devices http://www.rohitab.com/discuss/topic/41267-ssdpupnp-protocol-example/#

I am using Windows 10, both my laptop WiFi and WeMo switch are in same WiFi netowrk, disabled firewall. But I am not receiving any message. I had even tried changing the "Search Target" ST option to ssdp:all. The other sample code https://objectpartners.com/2014/03/25/a-groovy-time-with-upnp-and-wemo/ suggests to use ST as urn:Belkin:device:controllee:1, but there is no response from any device.

My Code:

#include <stdio.h>
#include <string>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#include <windows.h>
#include <stdio.h>
#include <conio.h>

#define SERVERPORT 1900
char buff[] = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 3\r\nST: upnp:rootdevice\r\n";

int main()
{
    char rcvdbuff[1000];
    int len, Ret = 2;

    WSADATA wsaData;
    struct sockaddr_in their_addr;
    SOCKET sock;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    sock = socket(AF_INET, SOCK_DGRAM, 0);

    their_addr.sin_family = AF_INET;

    their_addr.sin_addr.s_addr = inet_addr("239.255.255.250");
    their_addr.sin_port = htons(SERVERPORT);
    len = sizeof(struct sockaddr_in);

    while (1)
    {
        printf("buff:\n%s\n", buff);
        Ret = sendto(sock, buff, strlen(buff), 0, (struct sockaddr*)&their_addr, len);
        if (Ret < 0)
        {
            printf("error in SENDTO() function");
            closesocket(sock);
            return 0;
        }

        //Receiving Text from server
        printf("\n\nwaiting to recv:\n");
        memset(rcvdbuff, 0, sizeof(rcvdbuff));
        Ret = recvfrom(sock, rcvdbuff, sizeof(rcvdbuff), 0, (struct sockaddr *)&their_addr, &len);
        if (Ret < 0)
        {
            printf("Error in Receiving");
            return 0;
        }
        rcvdbuff[Ret - 1] = '\0';
        printf("RECEIVED MESSAGE FROM SERVER\t: %s\n", rcvdbuff);

        //Delay for testing purpose
        Sleep(3 * 1000);
    }
    closesocket(sock);
    WSACleanup();
}
yuvi
  • 25
  • 8
  • Your M-SEARCH message is a missing an empty line ("\r\n") in the end. – Jussi Kukkonen May 17 '17 at 21:17
  • @jku: Thanks a ton. Now I could able to get response from devices. But as it is running on a while loop, after sometime the receive call returns -1. Also I see WeMo switch responding only once. But I also have an ASUS wifi router which is responding continuously. Is it what expected? – yuvi May 18 '17 at 14:18
  • You should receive one answer per M-SEARCH (per responding service/device) but I guess your code won't handle more than one message per M-SEARCH.. . You'll need to look at errno to find out why recvfrom fails. – Jussi Kukkonen May 18 '17 at 14:58

0 Answers0