How-To use socket addresses in a portable way
POSIX networking APIs define struct sockaddr
, which provides a semi-portable
way for dealing with socket addresses. The structure is only semi-portable,
because its size is platform- and feature dependent, and dealing with those
differences can make code rather verbose.
With the liberate::net::socket_address
class, this library provides
a means for easily converting to and from struct sockaddr
, with bounds
checks on the underlying data structure.
The class is hashable and comparable, and therefore can easily be used as keys in C++ containers.
Convert from struct sockaddr
1#include <liberate/net/socket_address.h>
2
3struct sockaddr input;
4// Initialize with system APIs in whichever way is appropriate
5
6liberate::net::socket_address addr1{&input, sizeof(input)};
7liberate::net::socket_address addr2{&input, sizeof(input)};
8
9assert(addr1 == addr2);
You can now use such socket_address
instances with system APIs by using its
accessor functions.
Use where struct sockaddr is expected
1int ret = ::bind(fd,
2 reinterpret_cast<struct sockaddr const *>(addr.buffer()),
3 addr.bufsize());