Winsock,仅接受来自特定IP地址的请求 [英] Winsock, accept request only from specific IP address

查看:151
本文介绍了Winsock,仅接受来自特定IP地址的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使Winsock程序仅接受来自特定地址的连接请求?我希望被拒绝的连接被完全忽略而不是被TCP拒绝.

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.

推荐答案

要使Winsock程序仅接受来自特定IP地址的连接,请使用

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是您编写的函数,它决定堆栈是接受还是拒绝连接.如果拒绝,则远程对等方将获得一个TCP RST数据包,因此它知道它已被拒绝.

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.

如果您希望网络堆栈在不通知远程对等方的情况下静默丢弃来自其他地址的连接尝试,则必须在比Winsock更低的级别上执行此操作.在Vista或Windows Server 2008及更高版本上,此命令将修改防火墙规则以实现所需的效果:

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.

它表示允许IP 1.2.3.4的远程计算机连接到此计算机上的TCP端口1234.如果您在默认模式下启用了防火墙,该防火墙会拒绝不允许的流量,则所有其他计算机的连接尝试都将被丢弃.

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.

在Windows的较早版本上,回到XP,可以使用不同的"netsh防火墙"语法来获得相同的效果.只需在命令提示符下键入"netsh防火墙"即可开始遍历其内置帮助.

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.

这篇关于Winsock,仅接受来自特定IP地址的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆