-1
我有一个Raspberry Pi Zero W,我试图编写代码连接到。 bind()
命令失败,返回-1。我不能用BDADDR_ANY
,因为我得到的编译错误:临时Raspberry Pi bluez C++,为什么bind()函数返回-1(失败)?
我使用my_bdaddr_any
代替
取地址,但是那是什么得到-1回报。如果我使用
my_bdaddr_all
或my_bdaddr_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;
您是否检查过“errno”? –
我刚刚做了,并得到消息“地址已在使用”。这没有意义,但我更好地调查。我以前试图找出如何获得errno,但发现它是一个全局变量,由该函数设置,我需要做的就是添加下面的代码:'printf(“Bluetooth bind failed.ERRNO =%d \ n“,errno); char * errorMessage = strerror_r(errno,buf,1024); printf(“%s \ n”,errorMessage);' –