-
-
Notifications
You must be signed in to change notification settings - Fork 35.2k
socket bind vs SO_BINDTODEVICE #35769
Description
I'm exclusively speaking about client Socket on Linux, server socket is not an issue and other platforms behave differently.
This issue is not a setup issue (as mentioned on many of the issues closed), routing is not a solution, the use case is to connect to the same remote address on the same port with two different IP through two different interface based on software decisions. Routing won't solve this.
The only mechanism for socket binding is the option "localAddress", this simply binds the socket to a specific address.
In case of outbound connection, we have no way to force the outbound interface and most likely, when people create an outbound connection what they expect with this parameter is to bind the socket to an interface.
That makes little sense to bind to an address and still lets the kernel route the packets through another interface, it will probably lead to impossible routing of the response.
There is been some workaround using the private method _createHandle (node 10), to access the fs and set some socket options, but this is not possible in the latest versions (can still use nextTick after socket creation, but...).
There are two options :
- It could be safe to assume that and always bind to the corresponding interface when localAddress is set, the socket is an AF_INET and it's a client socket with
setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface, length) - Add an event on the Socket emitted when the socket is created (fd exists) and before the connection, as some of the socket options can't be set after that.
If it was about designing a new API, the first option would probably be the best one, but the second one is more robust and let people write libraries to do whatever they want with the socket, + leave to them the compatibility issues of those options with different platforms.
https://www.man7.org/linux/man-pages/man7/socket.7.html
https://codingrelic.geekhold.com/2009/10/code-snippet-sobindtodevice.html