0

Environment: Ubuntu 18.04

In my C++-based project, I have two different applications:

  • A Bluetooth server
  • A Bluetooth client

Once the BT server runs on one box, my BT client from another box can connect to the server app using the specified Bluetooth MAC address.

The Bluetooth MAC address is currently obtained by running "hciconfig hci0" on the server box. However, I would like to display this address programmatically.

Here is my BT initialization code on the server:

int s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

// bind socket to port 1 of the first available
// local bluetooth adapter
bdaddr_t bdaddrAny = {{0, 0, 0, 0, 0, 0}};
sockaddr_rc locAddr = {0, {0, 0, 0, 0, 0, 0}, 0};
locAddr.rc_family = AF_BLUETOOTH;
locAddr.rc_bdaddr = bdaddrAny;
locAddr.rc_channel = (uint8_t)1;
bind(s, (struct sockaddr *)&locAddr, sizeof(locAddr));

char addr[19] = {0};
ba2str(&locAddr.rc_bdaddr, addr);
fprintf(stderr, "BT server MAC address %s\n", addr);

However, even after a successful bind, the displayed address is 00:00:00:00:00:00.

Can someone please show me the correct way to obtain the MAC address of the BT socket the server is bound to? Regards.

Peter
  • 11,260
  • 14
  • 78
  • 155
  • "*even after a successful bind, the displayed address is 00:00:00:00:00:00*" - of course, because that is all `locAddr` contains. You are not doing anything to update `locAddr`. `bind()` will not update it. But, just like how a TCP server bound to `0.0.0.0` will not report individual local IPs when using things like `getsockname()` since the server is bound to ALL local interfaces, the same thing applies to Bluetooth bound to `bdaddrAny`, it is bound to ALL local Bluetooth adapters. You are going to have to manually enumerate local BT adapters to get the output you want to display. – Remy Lebeau Jul 07 '20 at 00:13
  • See if something like this works with your Bluetooth adapters: [MAC address with getifaddrs](https://stackoverflow.com/questions/6762766/) – Remy Lebeau Jul 07 '20 at 00:18

1 Answers1

0

Thank you all for your help. I came across the source code for hcitool.c that is part of Android platform. The trick is to use hci_for_each_dev function.

For those interested, you can find the code here: https://android.googlesource.com/platform/external/bluetooth/bluez/+/71716c2a00dc7e60055fe6589b87b77daed23a92/tools/hcitool.c

Peter
  • 11,260
  • 14
  • 78
  • 155