#define ICARCH_WIN32

#include <Windows.h>
#include <Iphlpapi.h>
#include <PeerSDK.h>
#include <stdio.h>

// Only for Windows
PeerSDK::IPAddress FindBestNIC()
{
    DWORD index = 0xFFFFFFFF;
    ::GetBestInterface(INADDR_ANY, &index);

    ULONG size = 0;
    DWORD r = ::GetIpAddrTable(NULL, &size, FALSE);

    BYTE* table = new BYTE[size];
    MIB_IPADDRTABLE* p = (MIB_IPADDRTABLE*)&table[0];
    r = ::GetIpAddrTable(p, &size, FALSE);

    for (int32 i = 0; i < (int32)p->dwNumEntries; i++)
    {
        if (p->table[i].dwIndex == index)
        {
            byte* ip = (byte*)&p->table[i].dwAddr;

            char notation[20] = "";
            sprintf(notation, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);

            delete[] table;
            return PeerSDK::IPAddress::Parse(notation);
        }
    }

    delete[] table;
    return PeerSDK::IPAddress::Any();
}

void PEERSDK_CALLBACK OnDiscoveryMatch(void* tag, PeerSDK::DiscoveryMatchEventArgs const& e)
{
    printf("%s\n", e.IP().ToString().ToAnsi());
    for (int i = 0; i < e.Services().Count(); i++)
        printf("    %s\n", e.Services()[i].ToAnsi());
}

void main()
{
     ::CoInitialize(NULL);

     PeerSDK::Peer::Startup();

     PeerSDK::DiscoveryService service;
     service.DiscoveryMatch().Add(NULL, OnDiscoveryMatch);
     service.Start(FindBestNIC());
     service.Probe(FindBestNIC(), PeerSDK::QName("http://i-dvr.net", "DVR"));
     ::Sleep(6000);
}
