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.
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
getpeernamefunction fromsys/socket.hon linux.If you're using Windows IOCP sockets, then the
native_handle_typewill 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.