C - 设置套接字选项L2CAP_OPTIONS失败并显示"Invalid argument error"



我有一个代码,我需要在其中创建一个 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);
}

您错误地调用getsockopt。最后一个参数应是指向soclen_t的指针:

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

在你的代码中,getsockoptsizeof(opts)视为指针(顺便说一句,你没有收到警告吗?(,导致未定义的行为。

此外,您必须使用通过调用获得option调用setsockoptgetsockopt

相关内容

最新更新