c++ 如何将蓝牙地址格式化为btaddr?

hgqdbh6s  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(295)

我有一个蓝牙地址(7 C9 EBD 4CBFB 2),我需要使用winsock连接到它。这是我的代码,它返回错误-1,并且不会连接到我的设备。我如何格式化这个地址以用作btaddr?谢谢。下面是我的代码:

#include <winsock2.h>
#include <ws2bth.h>
#pragma comment(lib, "Ws2_32.lib")
#include <Windows.h>
#include <iostream>
using namespace std;
SOCKADDR_BTH sockAddr;
SOCKET btSocket;
int error;

int main() {
    btSocket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
    memset(&sockAddr, 0, sizeof(sockAddr));
    sockAddr.addressFamily = AF_BTH;
    sockAddr.serviceClassId = RFCOMM_PROTOCOL_UUID;
    sockAddr.port = BT_PORT_ANY;
    sockAddr.btAddr = 0x7C9EBD4CBFB2;
    error = connect(btSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr));
    cout << error;
}
kwvwclae

kwvwclae1#

您没有在socket()之前调用WSAStartup()。如果您做了更好的错误检查,您会更快地意识到这一点。请参阅Handling Winsock Errors
socket()将返回INVALID_SOCKET(-1),然后WSAGetLastError()将返回WSANOTINITIALISED(10093)。
尚未执行成功的WSAStartup
应用程序尚未调用WSAStartupWSAStartup失败。应用程序可能正在访问当前活动任务不拥有的套接字(即,试图在任务之间共享套接字),或调用WSACleanup的次数太多。
然后connect()将失败,返回值为SOCKET_ERROR(-1),并且WSAGetLastError()将返回WSAENOTSOCK(10038)。
非套接字上的套接字操作。
试图在不是套接字的对象上执行操作。套接字句柄参数未引用有效的套接字,或者对于selectfd_set的成员无效。
根据Bluetooth Programming with Windows Sockets文档:
与所有Windows套接字应用程序编程一样,必须调用WSAStartup函数才能启动Windows套接字功能并启用蓝牙。
始终检查系统调用的错误代码!
试试这样的方法:

#include <winsock2.h>
#include <ws2bth.h>
#include <Windows.h>
#include <iostream>
#include <cstdio>
#pragma comment(lib, "Ws2_32.lib")

int str2ba(const char *straddr, BTH_ADDR *btaddr)
{
    int i;
    unsigned int aaddr[6];
    BTH_ADDR tmpaddr = 0;

    if (std::sscanf(straddr, "%02x:%02x:%02x:%02x:%02x:%02x",
                    &aaddr[0], &aaddr[1], &aaddr[2],
                    &aaddr[3], &aaddr[4], &aaddr[5]) != 6)
        return 1;
    *btaddr = 0;
    for (i = 0; i < 6; i++) {
        tmpaddr = (BTH_ADDR) (aaddr[i] & 0xff);
        *btaddr = ((*btaddr) << 8) + tmpaddr;
    }
    return 0;
}

int main() {
    WSADATA wsa;
    memset(&wsa, 0, sizeof(wsa));

    int error = WSAStartup(MAKEWORD(2,2), &wsa);
    if (error != 0) {
        std::cerr << "WSAStartup() failed, error: " << error;
        return -1;
    }

    SOCKET btSocket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
    if (btSocket == INVALID_SOCKET) {
        error = WSAGetLastError();
        std::cerr << "socket() failed, error: " << error;
        WSACleanup();
        return -1;
    }

    SOCKADDR_BTH sockAddr;
    memset(&sockAddr, 0, sizeof(sockAddr));
    sockAddr.addressFamily = AF_BTH;
    sockAddr.serviceClassId = RFCOMM_PROTOCOL_UUID;
    sockAddr.port = BT_PORT_ANY;
    str2ba("7C:9E:BD:4C:BF:B2", &sockAddr.btAddr);

    if (connect(btSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR) {
        error = WSAGetLastError();
        std::cerr << "connect() failed, error: " << error;
        closesocket(btSocket);
        WSACleanup();
        return -1;
    }

    // use btSocket as needed...

    closesocket(btSocket);
    return 0;
}

相关问题