setsocketoptions L2CAP_OPTIONS失败并显示“无效参数错误”

时间:2017-07-20 11:49:07

标签: c sockets bluetooth l2cap

我有一个代码,我需要创建一个L2CAP套接字,连接到一个设备并为其设置mtu。尝试这样做时,我收到错误“无效参数”。创建套接字,绑定到一个bd_address并且也完成连接。

 sk = socket(PF_BLUETOOTH, SOCK_RAW, BTPROTO_L2CAP);
 if (sk < 0) 
 {
     perror("Can't create socket");
 }

 /* Bind to local address */
 memset(&addr, 0, sizeof(addr));
 addr.l2_family = AF_BLUETOOTH;
 str2ba(LOCAL_DEVICE_ADDRESS, &addr.l2_bdaddr);

 if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0)
 {
      perror("Can't bind socket");
 }

 /* Connect to remote device */
 memset(&addr, 0, sizeof(addr));
 addr.l2_family = AF_BLUETOOTH;
 str2ba(REMOTE_DEVICE_ADDRESS, &addr.l2_bdaddr);

 if (connect(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) 
 {
    perror("Can't connect");
 }
 perror("connected");

 if (getsockopt(sk, SOL_L2CAP, L2CAP_OPTIONS, &opts, sizeof(opts)) < 0)
 {
    perror("Can't get L2CAP MTU options");
    close(sk);
 }

 opts.imtu = 672; //this is default value
 opts.omtu = 672; //tried changing this too

if (setsockopt(sk, SOL_L2CAP, L2CAP_OPTIONS, &opts, sizeof(opts)) < 0) 
{
    perror("Can't set L2CAP MTU options");
    close(sk);
}

1 个答案:

答案 0 :(得分:0)

您未正确致电getsockopt。最后一个参数应该是指向soclen_t

的指针
socklen_t optlen = sizeof(opts);
getsockopt(sk, SOL_L2CAP, L2CAP_OPTIONS, &opts, &optlen);

在您的代码getsockopt中将sizeof(opts)视为指针(顺便说一下,没有收到警告?),导致未定义的行为。

此外,您必须通过setsockopt来电获得option来致电getsockopt