简体   繁体   中英

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. 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);

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". The actual application in question (PHP XDebug) does not connect to the ip limited endpoint, but does otherwise.

"telnet localhost 9000" give the following error, but does connect. I don't connect have localhost in php.ini, but maybe this message is related. "Connection refused for::1:"

I think it would be proper to allow connections to::1: regardless of if this is the bug or not.

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 .

Hand this address to boost asio in order to listen to IPv6 connections:

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());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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