TIdTCPServer绑定localhost仍允许其他IP连接,Bindings用法存疑
IdTCPServer绑定localhost后仍允许外部连接的问题解决
你误用了SetPeer方法,这个方法的作用是限制服务器仅接受来自指定远程IP和端口的连接,不是用来设置服务器监听的本地地址。这就是外部IP依然能连接的核心原因——服务器实际上还是在所有网络接口(0.0.0.0)上监听,只是尝试过滤特定远程节点的连接,但这个逻辑并非用于绑定本地监听地址,限制效果完全无效。
要让服务器仅在localhost(127.0.0.1)上监听,必须使用SetBinding方法指定本地绑定的IP和端口,正确代码如下:
IdTCPServer.Bindings.Clear; IdTCPServer.Bindings.Add; IdTCPServer.Bindings.Items[0].SetBinding('127.0.0.1', 1001, False); //... IdTCPServer.Active := true;
也可以用更简洁的写法:
IdTCPServer.Bindings.Clear; with IdTCPServer.Bindings.Add do begin IP := '127.0.0.1'; Port := 1001; end; //... IdTCPServer.Active := true;
使用SetBinding后,服务器只会绑定到127.0.0.1这个本地回环接口,外部设备无法访问该端口,从而实现仅允许localhost连接的需求。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

