Bluetooth 树莓皮蓝莓C++;,为什么bind()函数返回-1(失败)?
我有一个树莓皮零W,我正试图写代码连接到。Bluetooth 树莓皮蓝莓C++;,为什么bind()函数返回-1(失败)?,bluetooth,bind,Bluetooth,Bind,我有一个树莓皮零W,我正试图写代码连接到。bind()命令因-1而失败。我无法使用BDADDR\u ANY,因为我得到一个编译错误: 临时立法会地址 我使用的是my\u bdaddr\u any,但这就是-1返回值。如果我使用my\u bdaddr\u all或my\u bdaddr\u local,绑定会工作,但accept()永远不会工作。以下是我的代码片段: char buf[1024] = {0}; int bluetoothSocket, client, bytes_read;
bind()
命令因-1而失败。我无法使用BDADDR\u ANY
,因为我得到一个编译错误:
临时立法会地址
我使用的是my\u bdaddr\u any
,但这就是-1返回值。如果我使用my\u bdaddr\u all
或my\u bdaddr\u local
,绑定会工作,但accept()
永远不会工作。以下是我的代码片段:
char buf[1024] = {0};
int bluetoothSocket, client, bytes_read;
struct sockaddr_rc loc_addr = {0};
struct sockaddr_rc client_addr = {0};
socklen_t opt = sizeof(client_addr);
bdaddr_t my_bdaddr_any = {0, 0, 0, 0, 0, 0};
bdaddr_t my_bdaddr_all = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
bdaddr_t my_bdaddr_local = {0, 0, 0, 0xff, 0xff, 0xff};
bluetoothSocket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = (bdaddr_t &) my_bdaddr_all;
loc_addr.rc_channel = (uint8_t) 1;
int ret = -1;
if(ret = bind(bluetoothSocket, (struct sockaddr *)&loc_addr, sizeof(loc_addr)) == -1)
{
printf("Bluetooth bind failed.\n");
return 0;
}
listen(bluetoothSocket, 1);
client = accept(bluetoothSocket, (struct sockaddr *)&client_addr, &opt);
if (client == -1)
{
close(client);"
}
ba2str(&loc_addr.rc_bdaddr, buf);
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
bytes_read = read(client, buf, sizeof(buf));
if (bytes_read > 0)
{
printf("Bluetooth bytes received [%s]\n", buf);
}
close(client);
close(bluetoothSocket);
return;
bind()问题是由于另一个正在运行的程序已绑定到蓝牙设备。我添加这段代码是为了找出为什么我一直在bind()上得到-1
您是否检查了
errno
?我刚刚检查了,收到消息“地址已在使用”。这没有道理,但我最好调查一下。我以前试图找出如何获取errno,但发现它是一个由函数设置的全局变量,我只需添加以下代码:printf(“蓝牙绑定失败。errno=%d\n”,errno);char*errorMessage=strerror\u r(errno,buf,1024);printf(“%s\n”,errorMessage)代码>
if (ret = bind(bluetoothSocket, (struct sockaddr *)&loc_addr, sizeof(loc_addr)) == -1)
{
printf("Bluetooth bind failed. ERRNO=%d\n", errno);
char *errorMessage = strerror_r(errno, buf, 1024);
printf("%s\n", errorMessage);
return 0;
}