clinuxsocketsclangmulticastsocket

Can't set SO_BINDTODEVICE for a socket on enp4s0


I have an old code running for linux (ubuntu 16.04) that binds to a socket and set SO_BINDTODEVICE,

setsockopt(sout, SOL_SOCKET, SO_BINDTODEVICE,"enp4s0", 4);

I have change the target to a new Ubuntu 17.10, and it fails with the error "No such device", I have tested in this target using loop back 'lo' interface and it works.

The interface have the multicast flag enabled

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: enp4s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether 00:0a:cd:21:ac:2a brd ff:ff:ff:ff:ff:ff
3: enp3s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
    link/ether 30:9c:23:1c:b9:08 brd ff:ff:ff:ff:ff:ff
4: enp0s31f6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether 30:9c:23:1c:b9:09 brd ff:ff:ff:ff:ff:ff
22: macvtap0@enp4s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 500
    link/ether 52:54:00:e4:5a:f8 brd ff:ff:ff:ff:ff:ff
23: macvtap1@enp0s31f6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 500
    link/ether 52:54:00:a0:93:d0 brd ff:ff:ff:ff:ff:ff

It fails in all interfaces but lo.

I suspect about the length of device name, so I've tested in a 17.04 and with the name "eno0" works, but with wlp5s0 (wifi) doesn't.

I don't know how to solve. Do you? Is there a limit in the length?


Solution

  • It's not working for longer name lengths because you're passing in the wrong length.

    The last argument to setsockopt specifies the length of the option value passed as the fourth argument. You're passing in a value of 4 for this option, so only the first 4 bytes of the string are looked at.

    Change the last argument to be the length of the string:

    setsockopt(sout, SOL_SOCKET, SO_BINDTODEVICE,"enp4s0", strlen("enp4s0"));