Skip to content

Instantly share code, notes, and snippets.

@alpereira7
Last active January 8, 2021 10:46
Show Gist options
  • Save alpereira7/2e3da086cbecf802a15f01468276ff65 to your computer and use it in GitHub Desktop.
Save alpereira7/2e3da086cbecf802a15f01468276ff65 to your computer and use it in GitHub Desktop.
Simple program that detects nearby Bluetooth devices.
// Simple program that detects nearby Bluetooth devices.
// Based on https://people.csail.mit.edu/albert/bluez-intro/c404.html#simplescan.c
// Enhanced with comments and personal notes.
// To compile:
// `gcc -o simplescan simplescan.c -lbluetooth`
// Install libbluetooth-dev:
// `sudo apt-get install libbluetooth-dev`
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // for close()
#include <sys/socket.h>
#include <string.h> // for memset()
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h> // for inquiry_info, IREQ_CACHE_FLUSH
#include <bluetooth/hci_lib.h> // for hci_get_route, hci_open_dev, hci_read_remote_name
int main(void){
// inquiry_info is a structure defined in hci.h
// it contains a field bdaddr which is the Bluetooth Device address.
inquiry_info *ii = NULL;
int max_rsp; // Maximum responses
int num_rsp; // Number of actual responses
int dev_id; // ID of Bluetooth adapter
int sock, len, flags;
int i;
char addr[19] = {0};
char name[248] = {0};
// Get Device ID
dev_id = hci_get_route(NULL); // NULL will be the first adapter, usually there is only one
// If we know adapter adress (`hciconfig -a`) we can also do
// bdaddr_t bdaddr = {0xDC, 0xA6, 0x32, 0xE4, 0x9C, 0x05};
// dev_id = hci_get_route(&bdaddr);
// or
// dev_id = hci_devid("DC:A6:32:E4:9C:12");
printf("dev_id = %d\n", dev_id);
// Get Socket ?
sock = hci_open_dev(dev_id);
printf("sock = %d\n", sock);
// Check Errors
if(dev_id < 0 || sock < 0) {
perror("opening socket");
exit(1);
}
len = 8;
max_rsp = 255;
flags = IREQ_CACHE_FLUSH; // = 1, hci_inquiry flush previously detected devices
ii = (inquiry_info*)malloc(max_rsp*sizeof(inquiry_info));
// hci_inquiry will fill ii with all the found responses
num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
if(num_rsp < 0)
perror("hci_inquiry");
printf("num_rsp = %d\n", num_rsp);
// Loop through Responses
for(i = 0; i < num_rsp; i++){
// Get Response Address
ba2str(&(ii+i)->bdaddr, addr);
memset(name, 0, sizeof(name));
// Get Response Name
if(hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name), name, 0) < 0)
strcpy(name, "[unknown]");
// Print name and address of scanned BT Devices
printf("%s %s\n", addr, name);
}
free(ii);
close(sock);
printf("OK!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment