2017-08-21 107 views
-1

我有一個Raspberry Pi Zero W,我試圖編寫代碼連接到。 bind()命令失敗,返回-1。我不能用BDADDR_ANY,因爲我得到的編譯錯誤:臨時Raspberry Pi bluez C++,爲什麼bind()函數返回-1(失敗)?

我使用my_bdaddr_any代替

取地址,但是那是什麼得到-1回報。如果我使用my_bdaddr_allmy_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; 
+0

您是否檢查過「errno」? –

+0

我剛剛做了,並得到消息「地址已在使用」。這沒有意義,但我更好地調查。我以前試圖找出如何獲得errno,但發現它是一個全局變量,由該函數設置,我需要做的就是添加下面的代碼:'printf(「Bluetooth bind failed.ERRNO =%d \ n「,errno); char * errorMessage = strerror_r(errno,buf,1024); printf(「%s \ n」,errorMessage);' –

回答

0

bind()問題是由於另一個正在運行的程序已經綁定到藍牙設備。我添加了這段代碼,以便了解爲什麼我一直在bind()上獲取-1。

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; 
}