linux Bluetooth programming in c

后端 未结 4 1183
死守一世寂寞
死守一世寂寞 2021-02-04 10:31

I am trying to run a basic code of c in linux[ubuntu] to search bluetooth device, but i am facing some problem.

By using command sudo apt-get install bluez,

4条回答
  •  遥遥无期
    2021-02-04 11:25

    Maybe you didn't include the essential header.

    here's an example of code to scan for bluetooth devices

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    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;
    }
    

    to compile it on linux, just do

    gcc -o simplescan simplescan.c -lbluetooth
    

    EDIT:

    Original code can be found in here

提交回复
热议问题