============================================= 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 :cpp:class:`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. .. seealso:: - :doc:`cpp-comparison` - :doc:`cpp-hashing` .. sourcecode:: cpp :linenos: :dedent: :caption: Convert from struct sockaddr #include struct sockaddr input; // Initialize with system APIs in whichever way is appropriate liberate::net::socket_address addr1{&input, sizeof(input)}; liberate::net::socket_address addr2{&input, sizeof(input)}; assert(addr1 == addr2); You can now use such ``socket_address`` instances with system APIs by using its accessor functions. .. sourcecode:: cpp :linenos: :dedent: :caption: Use where struct sockaddr is expected int ret = ::bind(fd, reinterpret_cast(addr.buffer()), addr.bufsize());