-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);' –