Accessing underlying data of Boost Asio socket

108 views Asked by At

I am trying to access the underlying data of a socket like the remote endpoint, it's address and port number. Below is a portion of code copying the remote endpoint from a connected socket. Is it possible to get a reference / const reference to the remote endpoint (actual data)? (so no copying is involved).

auto remoteEp = peerSocket.remote_endpoint();
auto IPaddress = remoteEp.address();
auto portNumber = remoteEp.port();

This is only attempted if the socket is connected to a remote client.

1

There are 1 answers

1
sehe On

That's not possible. It presupposes that those objects have copies of that data internally. Which they may or may not (they actually don't).

Instead the functions use the getpeername function from sys/socket.h on linux.

On windows or cygwin, Asio will actually cache the remote endpoint by checking whether the connection time is still the same as when it was last retrieved. This still means you cannot have a reference.

If you're using Windows IOCP sockets, then the native_handle_type will optionally contain a copy of the remote endpoint, which can be checked with .have_remote_endpoint() and retrieved with .remote_endpoint() (still by value).

Summary

References are unsafe in concurrency scenarios. Object lifetimes are not dependable in a world with async operations.

I sense that your question may be driven by a need for optimization. In that case, by far the simplest option will be to simply cache the value yourself in a place where you control the lifetime of the object.