Trying to bind an already bound TCP port should raise exception ("bind: Address already in use" exception).
It does happen under Linux. But under Windows , no exception is raised..
Could it be because u开发者_Python百科nder windows it tries to bind to ANY interface? but in Linux it tries to bind to ALL of them and raise an exception if not all of them are bound ?
Here is the code snippet:
try {
tcp::endpoint endpoint(tcp::v4(), 8081);
tcp::acceptor acceptor(io_service);
acceptor.open(endpoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.set_option(tcp::acceptor::enable_connection_aborted(true));
acceptor.bind(endpoint);
acceptor.listen(1024)
catch(std::exception &e) {
cout << e.what() << endl;
}
In windows, the option tcp::acceptor::reuse_address
is equivalent to calling setsockopt
and specifying SO_REUSEADDR
. This specifically allows multiple sockets to be bound to an address even if it is in use. See the MSDN documentation here.
There's a corresponding option in Win32 (SO_EXCLUSIVEADDRUSE
) which is documented here. This post details some potential drawbacks with simply using SO_REUSEADDR
on Win32 platforms.
精彩评论