I use the following code to determine if I can use the Windows Bluetooth stack and if the required hardware is present.
CanUseBluetooth() simply checks that there's a winsock provider that understands the bluetooth protocol. If that's the case then the stack is installed.
static bool CanUseBluetooth(
bool throwOnFailure)
{
static const CAddressTypeBluetooth addressType;
SOCKET s = ::socket(addressType.Family(), SOCK_STREAM, addressType.Protocol());
const bool canUseBluetooth = (s != INVALID_SOCKET);
const DWORD lastError = ::GetLastError();
::closesocket(s);
if (!canUseBluetooth && throwOnFailure)
{
throw CWin32Exception(_T("CUsesXPBluetooth::CanUseBluetooth()"), lastError);
}
return canUseBluetooth;
}
HarwareActive() checks that we can bind to the wildcard address, if we can do that then we have some active bluetooth hardware that's using the Windows stack.
static bool HardwareActive(
bool throwOnFailure)
{
static const CAddressTypeBluetooth addressType;
SOCKET s = ::socket(addressType.Family(), SOCK_STREAM, addressType.Protocol());
if (s == INVALID_SOCKET)
{
const DWORD lastError = ::GetLastError();
::closesocket(s);
throw CWin32Exception(_T("CUsesXPBluetooth::HardwareActive() - CanUseBluetooth"), lastError);
}
bool hardwareActive = true;
static const IAddress &address = addressType.WildcardAddress();
if (SOCKET_ERROR == ::bind(s, &address.AsSockAddr(), address.Size()))
{
hardwareActive = false;
}
const DWORD lastError = ::GetLastError();
::closesocket(s);
if (!hardwareActive && throwOnFailure)
{
throw CWin32Exception(_T("CUsesXPBluetooth::HardwareActive()"), lastError);
}
return hardwareActive;
}