views:

98

answers:

1

How can I make a Winsock program accept connection requests only from specific addresses? I would like denied connections to be ignored completely rather than get a TCP rejection.

+4  A: 

To make a Winsock program accept connections from only particular IP addresses, use the conditional accept mechanism of WSAAccept(). First, enable the feature:

SOCKET sd = socket(...);
listen(sd, ...);
DWORD nTrue = 1;
setsockopt(sd, SOL_SOCKET, SO_CONDITIONAL_ACCEPT, (char*)&nTrue, sizeof(nTrue));

Then, modify your accept call to look something like this:

sockaddr_in sin;
WSAAccept(sd, (sockaddr*)&sin, sizeof(sin), ConditionalAcceptChecker, 0);

ConditionalAcceptChecker is a function you write, which makes the decision about whether the stack will accept or reject the connection. If it rejects it, the remote peer gets a TCP RST packet, so it knows it was rejected.

If you want the network stack to silently drop connection attempts from other addresses without notifying the remote peer, you have to do that at a lower level than Winsock. On Vista or Windows Server 2008 and above, this command will modify the firewall rules to give the effect you want:

netsh advfirewall firewall add rule name=MyProtocol dir=in remoteip=1.2.3.4
                                    localport=1234 protocol=tcp action=allow

That's a single command, split due to formatting limitations on Stack Overflow.

What it says is that the remote machine at IP 1.2.3.4 is allowed to connect to TCP port 1234 on this machine. If you have the firewall enabled in its default mode, which rejects traffic not specifically allowed, connection attempts from all other machines will be dropped.

On older versions of Windows, going back to XP, there is a different "netsh firewall" syntax for getting the same effect. Just type "netsh firewall" at a command prompt to start walking through its built-in help.

Warren Young
if winsock can be configured not to reject, but discard traffic from undesired addresses
Updated answer above to cover firewall-level accept/reject control.
Warren Young
+1, didn't know of the feature in `WSAAccept`
Default