How to fill sockaddr_storage?

c++, sockets

Solution

The name is the hint, `sockaddr_storage` is for storage only, not for accessing. Use in a union with specific protocol structures:

union {
  struct sockaddr         sa;
  struct sockaddr_in      s4;
  struct sockaddr_in6     s6;
  struct sockaddr_storage ss;
} addr;
memset (&addr.s4, 0, sizeof(struct sockaddr_in));
addr.s4.sin_family = AF_INET;
addr.s4.sin_addr.s_addr = INADDR_ANY;

or `memcpy`, e.g.

struct sockaddr_storage storage;
struct sockaddr_in sin;

memset (&sin, 0, sizeof (sin));
sin.sin_family = AF_INET
sin.sin_addr.s_addr = inet_addr ("127.0.0.1");
memcpy (&storage, &sin, sizeof (sin));

Problem

I am trying to use `sockaddr_storage` struct in my application. I am curious how to fill it. For example I have following code: ``` sHostAddr.sin_family = AF_INET; sHostAddr.sin_addr.s_addr = inet_addr (cpIPAddress); ``` How can I replace it if I use `sockaddr_storage` struct? I know that there are some char arrays, and I suppose I can get an equivalent code using some array index offsets? Thanks on advance.

Original source