简体   繁体   English

如何将 boost asio 接受器限制为本地主机和/或本地网络?

[英]How can I limit a boost asio acceptor to localhost and/or local networks?

I am trying to figure out how to limit a tcp socket to localhost.我想弄清楚如何将 tcp 套接字限制为本地主机。 I finally found code that will compile, but it does not accept any connections.我终于找到了可以编译的代码,但它不接受任何连接。

The code accepts connections with endpoint_all, but not with "endpoint_local" variable set with tcp::endpoint(ip::address::from_string("127.0.0.1"),port2);该代码接受与 endpoint_all 的连接,但不接受使用 tcp::endpoint(ip::address::from_string("127.0.0.1"),port2) 设置的“endpoint_local”变量的连接;

boost::asio::io_service io_service;
short port = 9000;
tcp::endpoint endpoint_all   = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),port);
tcp::endpoint endpoint_local = boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"),port);
try
{
    server s(io_service, std::atoi("9000"),endpoint_all);

    io_service.run();
}
catch (std::exception& e)
{
}

Update: I can access the socket via "telnet 127.0.0.1 9000" and "telnet localhost 9000".更新:我可以通过“telnet 127.0.0.1 9000”和“telnet localhost 9000”访问套接字。 The actual application in question (PHP XDebug) does not connect to the ip limited endpoint, but does otherwise.有问题的实际应用程序 (PHP XDebug) 没有连接到 ip 受限端点,而是以其他方式连接。

"telnet localhost 9000" give the following error, but does connect. “telnet localhost 9000”给出以下错误,但确实连接。 I don't connect have localhost in php.ini, but maybe this message is related.我没有在 php.ini 中连接本地主机,但也许这条消息是相关的。 "Connection refused for::1:" “连接被拒绝 ::1:”

I think it would be proper to allow connections to::1: regardless of if this is the bug or not.我认为允许连接到 ::1: 是正确的,不管这是否是错误。

Trying ::1...
telnet: connect to address ::1: Connection refused
Trying fe80::1...
telnet: connect to address fe80::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.

Judging from the error message "Connection refused for::1" it seems that PHP XDebug tries to connect to ::1 which is the IPv6 equivalent of 127.0.0.1 .从错误消息“Connection refused for ::1”来看,PHP XDebug 似乎试图连接到::1 ,它是127.0.0.1的 IPv6 等价物。

Hand this address to boost asio in order to listen to IPv6 connections:将此地址传递给 boost asio 以监听 IPv6 连接:

tcp::endpoint endpoint_local = tcp::endpoint(boost::asio::ip::address::from_string("::1"),port);

Do it like that那样做

boost::asio::ip::tcp::resolver resolver(io_service);

resolver.async_resolve({"localhost", std::to_string(port).data()}, [self{shared_from_this()}](auto ec, auto res) {
    if(ec || res.empty()) {
        return;
    }
    auto endpoint = boost::asio::ip::tcp::endpoint(*res.begin());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM