最近搞蓝牙,自己找网上的例子尝试编译,中间遇到了一些坑,记录一下:

#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<stdlib.h>#include<poll.h>#include<bluetooth/bluetooth.h>#include<bluetooth/hci.h>#include<bluetooth/hci_lib.h>#include<bluetooth/l2cap.h>void*Read_thread(void*pSK);intmain(intargc,char**argv){intiRel=0;intsk=0;structsockaddr_l2local_addr;structsockaddr_l2remote_addr;intlen;intnsk=0;pthread_tnth=0;structl2cap_optionsopts;intoptlen=0;intslen=0;charstr[16]={0};if(argc<2){printf("\nUsage:%spsm\n",argv[0]);exit(0);}//createl2capsocketsk=socket(PF_BLUETOOTH,SOCK_SEQPACKET,BTPROTO_L2CAP);//发送数据,使用SOCK_SEQPACKET为好if(sk<0){perror("\nsocket():");exit(0);}//bindlocal_addr.l2_family=PF_BLUETOOTH;local_addr.l2_psm=htobs(atoi(argv[argc-1]));//lastpsmbacpy(&local_addr.l2_bdaddr,BDADDR_ANY);iRel=bind(sk,(structsockaddr*)&local_addr,sizeof(structsockaddr));if(iRel<0){perror("\nbind()");exit(0);}//getopts//inmtu和outmtu.每个包的最大值memset(&opts,0,sizeof(opts));optlen=sizeof(opts);getsockopt(sk,SOL_L2CAP,L2CAP_OPTIONS,&opts,&optlen);printf("\nomtu:[%d].imtu:[%d].flush_to:[%d].mode:[%d]\n",opts.omtu,opts.imtu,opts.flush_to,opts.mode);//setopts.defaultvalueopts.omtu=0;opts.imtu=672;if(setsockopt(sk,SOL_L2CAP,L2CAP_OPTIONS,&opts,sizeof(opts))<0){perror("\nsetsockopt():");exit(0);}//listeniRel=listen(sk,10);if(iRel<0){perror("\nlisten()");exit(0);}len=sizeof(structsockaddr_l2);while(1){memset(&remote_addr,0,sizeof(structsockaddr_l2));nsk=accept(sk,(structsockaddr*)(&remote_addr),&len);if(nsk<0){perror("\naccept():");continue;}ba2str(&(remote_addr.l2_bdaddr),str);printf("\npeerbdaddr:[%s].\n",str);//得到peer的信息iRel=pthread_create(&nth,NULL,Read_thread,&nsk);if(iRel!=0){perror("pthread_create():");continue;}pthread_detach(nth);//分离之}return0;}void*Read_thread(void*pSK){//structpollfdfds[10];structpollfdfds[100];charbuf[1024]={0};intiRel=0;intexit_val=0;//fds[0].fd=*(int*)pSK;//fds[0].events=POLLIN|POLLHUP;fds[0].fd=(int)(*(int*)pSK);fds[0].events=POLLIN|POLLHUP;while(1){if(poll(fds,1,-1)<0){perror("\npoll():");}if(fds[0].revents&POLLHUP){//hangupprintf("\n[%d]Hangup\n",*(int*)pSK);close(*(int*)pSK);pthread_exit(&exit_val);break;}if(fds[0].revents&POLLIN){memset(buf,0,1024);//readdataiRel=recv(*(int*)pSK,buf,572,0);//printf("\nHandle[%d]Receive[%d]data:[%s]",*(int*)pSK,iRel,buf);}}return0;}

头文件:

#include<bluetooth/bluetooth.h>#include<bluetooth/hci.h>#include<bluetooth/hci_lib.h>#include<bluetooth/l2cap.h>

需要从以下网址下载两个文件:


http://www.bluez.org/download/


其中,头文件在bluez-5.38.tar.xz文件中有。


链接需要库文件libbluetooth.so.2

这个文件就要通过bluez-libs-3.36.tar.gz编译生成,执行两条命令就可以生成:

./configuremake

将生成的库文件拷贝到/usr/lib目录下就可以了。


gcc编译的时候要加编译选项,这样才能编译成功:

gccserver.c-oserver-Ibluez-5.38/lib/-lbluetooth-lpthread