I have a ServerSocket that I do not want listening on all interfaces, but I need it accessible from more than one interface. Anybody got any clever ideas besides running two sockets?
You could control it with the firewall.
Sure, I just try not to have anything listen anywhere I don’t need it. Relying on the firewall is not my plan A.
If you are trying to bind a single ServerSocket instance to multiple interfaces selectively, I’m pretty sure it can’t be done due to the way sockets work at the OS.
The physical interfaces will always see every electrical pulse that appears on their wire and it’s up to the kernel to make logical sense of that. It can be implied that what the kernel does is filter out stuff the application connected to a socket is not interested in.
The default ‘all interfaces’ listen state essentially causes the kernel to pass all connection requests to the socket with the matching port number. If you only want to see connection requests from a selected interface you need to set the interface field in the socket structure to tell the kernel the mac address you are interested in. There is only one interface field per socket structure however.
Options:
-
Set the NetworkInterface property of the ServerSocket. This prevents connection requests to other interfaces reaching your application. There is only one NetworkInterface field however. For multiple interfaces you need multiple ServerSocket instances.
-
To use a single ServerSocket instance you need to do the filtering yourself. The ServerSocket does not populate the socket NetworkInterface field but you can use the LocalIP field to identify connections you do or do not want to respond to.
-
Although ServerSocket does not populate the socket NetworkInterface field it can be set in AddSocket and appears to remain intact in the socket Connected event.