且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Linux上直接控制HCI设备(绕过蓝牙驱动程序)

更新时间:2021-08-06 21:54:45

我能够实现选项#1.

挖掘Linux内核代码中的蓝牙驱动程序,我找到了用于将HCI套接字与hci_channel=1绑定的选项. HCI_USER_CHANNEL的枚举是1,它导致驱动程序不向HCI设备添加自己的命令.

Digging in the Linux kernel code for bluetooth drivers, I found an option for binding an HCI socket with hci_channel=1. 1 is the enum for HCI_USER_CHANNEL which causes the driver not to add its own commands to the HCI device.

要在C语言中实现此目标:

struct sockaddr_hci {
    sa_family_t     hci_family;
    unsigned short  hci_dev;
    unsigned short  hci_channel;
};

struct sockaddr_hci a;

memset(&a, 0, sizeof(a));
a.hci_family = AF_BLUETOOTH;
a.hci_dev = 0; //0 for hci0
a.hci_channel = 1; //1 for HCI_CHANNEL_USER

bind(sock, (struct sockaddr *) &a, sizeof(a));

要在Python中实现此目的:

Python的套接字模块不支持此选项. Scapy中实现了针对Python中缺少支持的解决方法: https://github.com/secdev/scapy/blob/d2f2b0c7b46b607fcdf79860f8f866446bb625fb/scapy/layers/bluetooth.py#L808

Python's socket module does not support this option. A workaround for the missing support in Python was implemented in Scapy: https://github.com/secdev/scapy/blob/d2f2b0c7b46b607fcdf79860f8f866446bb625fb/scapy/layers/bluetooth.py#L808

C ++示例: https://github.com/sandeepmistry/node-bluetooth-hci-socket/blob/560a956c3e1421e31366115444ca9027d45b0e71/src/BluetoothHciSocket.cpp#L184

如果您对Linux内核的相关部分感兴趣:

If you are interested in the relevant part of the Linux kernel: https://github.com/torvalds/linux/blob/86292b33d4b79ee03e2f43ea0381ef85f077c760/net/bluetooth/hci_sock.c#L1693