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.
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));
You need to cast it. If for example your sin_family
is AF_INET6
, you can cast the sockaddr_storage
pointer to a sockaddr_in6
pointer and then fill in whatever you need to.
It is just a general socket address holding structure, big enough to hold either
struct sockaddr_in
or struct sockaddr_in6
data or any future sockaddr_xxx
..
You can find one example usage here: http://www.kame.net/newsletter/19980604/
Note that sometimes developers will redefine this structure to use a union instead. That can have some side effects and isn't cross-platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With