Search code examples
csocketsnetwork-interface

Send packets from a specific interface in c


I've been doing some socket programing in c and I would like to let the user of my program specify the interface to send and receive packets from. The linux man page for socket(7) says that you can set the socket option SO_BINDTODEVICE to bind the socket to a particular device such as "eth0". It also occurred to me that when calling bind() you typically pass it a sockaddr_in struct with the sin_addr.s_addr property set to INADDR_ANY to tell the socket to bind to all interfaces as shown below

int sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

struct sockaddr_in local;

local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
local.sin_port = 0;

bind(sd, (struct sockaddr *)&local, sizeof local);

If the point of passing in the sockaddr to bind is to specify where to bind the socket locally on your machine, could you just pass in the IP address of a specific interface to bind your socket to it? I was hoping someone could clarify what the socket is doing here, and what the difference is between that approach and using setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, &devicename, sizeof devicename); before you bind.

Note: In the example above I used UDP and removed error checking for simplicity, Ideally the answer to the above question should be able to work independently of the protocol being used.


Solution

  • If the point of passing in the sockaddr to bind is to specify where to bind the socket locally on your machine, could you just pass in the IP address of a specific interface to bind your socket to it?

    Binding to an address (via bind()) and binding to an interface (via setsockopt()) serve different, but overlapping purposes. Usually bind() is what you want.

    In particular, your question seems to assume that there is a 1:1 mapping between addresses and interfaces, but that it is not a safe assumption. One interface can have multiple addresses, and, at least in principle, one address can be served by multiple interfaces.