用C语言编写Linux蓝牙编程

16

我正在尝试在Linux[Ubuntu]中运行一段基本的C代码以搜索蓝牙设备,但是我遇到了一些问题。

使用命令sudo apt-get install bluez安装所需的blueZ库时,它说bluez已经是最新版本。

但是在编译C源代码时,使用gcc -o simplescan simplescan.c -lbluetooth命令时会出现错误,无法找到bluetooth.h和其他文件。

是否有完整的库包,或者我必须下载这些头文件?

我正在按照链接中的步骤进行操作。


我不是C++程序员,但我认为你需要源代码。Bluetooth.h是一个C++头文件。 - René Höhle
11
尝试执行命令 apt-get install libbluetooth-dev 安装蓝牙开发库。 - Piotr Praszmo
apt-get无法工作,我可以从https://launchpad.net/ubuntu/lucid/+source/bluez/4.60-0ubuntu8下载这个软件包吗? - Himanshu Pradhan
我无法使用apt-get命令,因为我没有连接到互联网,但如果我从外部下载这些库并通过U盘在我的Ubuntu PC上使用,是否可以实现?1)Glib库,2)Dbus库,3)Bluez,4)Bluez工具程序。 - Himanshu Pradhan
这里有一个关于蓝牙的好链接,适用于未来在DrDubbs的工作。 - EsmaeelE
4个回答

11

这解决了我的问题:

apt-get install libbluetooth-dev 

2
如果可能的话,请解释该命令的作用以及它如何解决问题。 - Keivan Esbati
这个答案让我在我的Ubuntu系统上安装了PyBluez。 - Gustavo Alejandro Castellanos

10

也许您没有包含必要的标题。

这是一个扫描蓝牙设备的代码示例。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

int main(int argc, char **argv)
{
    inquiry_info *ii = NULL;
    int max_rsp, num_rsp;
    int dev_id, sock, len, flags;
    int i;
    char addr[19] = { 0 };
    char name[248] = { 0 };

    dev_id = hci_get_route(NULL);
    sock = hci_open_dev( dev_id );
    if (dev_id < 0 || sock < 0) {
        perror("opening socket");
        exit(1);
    }

    len  = 8;
    max_rsp = 255;
    flags = IREQ_CACHE_FLUSH;
    ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));

    num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
    if( num_rsp < 0 ) perror("hci_inquiry");

    for (i = 0; i < num_rsp; i++) {
        ba2str(&(ii+i)->bdaddr, addr);
        memset(name, 0, sizeof(name));
        if (hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name), 
            name, 0) < 0)
        strcpy(name, "[unknown]");
        printf("%s  %s\n", addr, name);
    }

    free( ii );
    close( sock );
    return 0;
}

在Linux上编译它,只需要执行以下命令:

gcc -o simplescan simplescan.c -lbluetooth

编辑:

原始代码可在这里找到。


你是自己写的这段代码还是从somewhere获取的? - Daniel
12
因为你在回答中忘记提到它了。 - Daniel
需要安装库文件:sudo apt-get install libbluetooth-dev 在编译之前。 - Vijay Panchal

3
据我所知,这些头文件没有提供任何软件包。您需要从互联网上下载以下头文件:
1. `bluetooth.h` 2. `hci.h` 3. `hci_lib.h`
在您的主机上创建一个名为“bluetooth”的目录,在`/usr/lib/`下,并将上述头文件复制到`/usr/lib/bluetooth/`中。然后编译您的程序,它应该可以工作了。
注意:在编译时链接使用`-lbluetooth`。

1

您需要安装linux-headers软件包。在Ubuntu或Debian上,可以通过执行以下操作来完成此操作:

sudo apt install linux-headers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接