setsocketoptions L2CAP_OPTIONS fails with "Invalid argument error"

895 Views Asked by At

I have a code where I need to create a L2CAP socket, connect to a device and set mtu for the same. I am getting the error "Invalid argument" when trying to do so. The socket is created, binding is done to one bd_address and connect is also done.

 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

There are 1 best solutions below

2
On

You call getsockopt incorrectly. The last argument shall be a pointer to soclen_t:

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

In your code getsockopt treats sizeof(opts) as a pointer (BTW, didn't you get a warning?), causing undefined behavior.

Also, you must call setsockopt with option obtained by getsockopt call.