我的c程序应该监听传入的蓝牙连接。我在http://people.csail.mit.edu/albert/bluez-intro/x502.html阅读了这个例子,所以我有以下代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth.h>
#include <rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
int s, client, bytes_read;
socklen_t opt = sizeof(rem_addr);
// allocate socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
printf("socket: %d \n", s);
// bind socket to port 1 of the first available
// local bluetooth adapter
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = *BDADDR_ANY;
loc_addr.rc_channel = (uint8_t) 1;
bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
// put socket into listening mode
printf("put socket into listening mode \n");
listen(s, 1);
// accept one connection
printf("accept one connection \n");
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
printf("close connection");
// close connection
close(client);
close(s);
return 0;
}
但不是等待传入的连接请求,而是立即连接到地址00:00:00:00:00:00(see Linux terminal output here)。所以我的程序启动,将套接字设置为侦听模式,从00:00开始接受连接......然后再次关闭连接。我不知道00:00 ...地址代表什么,但它绝对不是我要连接的计算机的地址。
顺便说一句,蓝牙适配器工作正常,扫描设备工作,也可以使用终端中的默认蓝牙命令连接到其他计算机。但是我需要在c程序中执行此操作来分析传入的消息。
感谢您的帮助